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',
};
8
  • Have you tried using require()? Commented Jun 21, 2022 at 19:31
  • 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. Commented Jun 21, 2022 at 19:47
  • node-fetch v3 now distributes ES modules. If you're emitting CommonJS, you'll have to downgrade to v2. Commented Jun 21, 2022 at 20:20
  • @jonrsharpe 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? Commented Jun 21, 2022 at 22:28
  • In case anyone else is struggling with this - I ended up downgrading to v2 of node fetch. I couldn't find any other solution. Commented Jun 22, 2022 at 13:28

1 Answer 1

27

Please use v2 which remains compatible with CommonJS:

npm install node-fetch@2
const fetch = require('node-fetch');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.