Error "SyntaxError: Cannot use import statement outside a module" when using node-fetch in Jest with Typescript
Asked Answered
C

1

11

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',
};
Cimabue answered 21/6, 2022 at 19:18 Comment(8)
Have you tried using require()?Sleuth
That doesn't work unfortunately - it gives the error Cannot 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.Cimabue
node-fetch v3 now distributes ES modules. If you're emitting CommonJS, you'll have to downgrade to v2.Namara
@Namara Thanks for your reply, could you explain a bit more? I actually don't mind what kind of JS I emit, so would I be able to change my TS settings to emit ES and get it working?Cimabue
In case anyone else is struggling with this - I ended up downgrading to v2 of node fetch. I couldn't find any other solution.Cimabue
If you can't redeclare fetch, try using const nodeFetch = require("node-fetch"), then await nodeFetch("...")Sleuth
@Sleuth That also doesn't work for meCimabue
Oh, then sorry about that. Hope you can solve it soon!Sleuth
K
27

Please use v2 which remains compatible with CommonJS:

npm install node-fetch@2
const fetch = require('node-fetch');
Kitten answered 30/7, 2022 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.