I am trying to write an integration test in Typescript with Jest which uses node-fetch
, like this:
import fetch from 'node-fetch';
test('Hello', async () => {
await fetch("http://www.google.com");
});
But I am getting the following error:
Jest encountered an unexpected token
[...]
Details:
/home/xxx/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 | test('Hello', async () => {
4 | await fetch("http://www.google.com");
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (temp.test.ts:1:1)
I have tried some of the solutions given in other questions but they don't work; I think that my problem is slightly different because does not prevent me from using ES6-style important in general, but it specifically does not work for node-fetch
. For example, I can do import express from 'express'
without any difficuly.
To reproduce this error, I ran:
npm init
npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
npx ts-jest config:init
npx jest
which yields the following Jest config:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
require()
? – SleuthCannot redeclare block-scoped variable 'fetch'.ts(2451), lib.dom.d.ts(18095, 18): 'fetch' was also declared here.
. Even if I give it a different name, it still doesn't work. – Cimabuefetch
, try usingconst nodeFetch = require("node-fetch")
, thenawait nodeFetch("...")
– Sleuth