Skip to content

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

Closed
@roblframpton

Description

@roblframpton

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 believe this is specifically a problem with node-fetch because it only affects imports from this package. For example, I can do import express from 'express' without any difficulty.

Reproduction

Steps to reproduce the behavior:

  1. Run the following:
npm init
npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
npx ts-jest config:init
  1. Create the file temp.test.ts:
import fetch from 'node-fetch';

test('Hello', async () => {
    await fetch("http://www.google.com");
});
  1. Run npx jest

Expected behavior

The test calls fetch

Your Environment

software version
node-fetch 3.2.6
node v16.0.0
npm 8.5.5
jest 28.1.1
Operating System Windows 10 x64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions