I'm trying to setup a very simple NPM codebase that I can use to drive an API to do some testing.
The line of code causing the error is just import fetch from "node-fetch";
, see the code.
For the setup/configuration, I'm following this repository (suggestions for a better template to use would be appreciated): https://github.com/bromix/typescript-jest-example
When I try to use the node-fetch
library in my code (either in a test.ts
file in the /test
directory or a .ts
file in the /src
directory) - I get the following error:
FAIL test/Api.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
...
Details:
C:\ardc\rats\node_modules\node-fetch\src\index.js:9
import http from 'node:http';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import fetch from "node-fetch";
| ^
2 |
3 | const apiBase = "https://api.raid.org.au/v1";
4 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/RaidApi.ts:1:1)
I gather there's something weird about node-fetch v3.x having upgraded to be an esmodule, as stated in this answer here: https://mcmap.net/q/417432/-node-fetch-3-0-0-and-jest-gives-syntaxerror-cannot-use-import-statement-outside-a-module
But I've tried frobbing a bunch of different things in package.json
and tsconfig.json
but I can't get it work.
What change do I need to make so my tests can use node-fetch
to make request calls?
The whole point of the repo is just to make these HTTP calls, so there's no compatibility problems to consider with changing module type or whatever needs doing.
My workaround is to downgrade to node-fetch
2.6.7
as shown here. But if this esmodule stuff is the way forward, I'd like to figure out how to make it work.
You can see the entire failing project here: https://github.com/ardc-shorn/rats/tree/0cdf2cf1ff4bc9e7ef0fa6113db9b9ff9f6cc6c9
But, to have a self-cointained question, here's the important config.
package.json: {
"name": "rats",
"version": "0.0.1",
"description": "RAiD API Test Suite",
"scripts": {
"build": "tsc",
"test": "jest"
},
"devDependencies": {
"@types/jsonwebtoken": "8.5.8",
"jsonwebtoken": "8.5.1",
"node-fetch": "3.2.6",
"@types/jest": "28.1.1",
"jest": "28.1.1",
"ts-jest": "28.0.5",
"typescript": "4.7.3",
"ts-node": "10.8.1"
}
}
tsconfig.json: {
"include": ["./src/**/*"],
"exclude": ["node_modules"],
"compilerOptions": {
"target": "ES5",
"module": "CommonJS",
"outDir": "./out",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
jest.config.js:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};