Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
Unable to run JEST test

I'm facing an issue when I try to import something using require() function in jest test file.

script2.test.js

const fetch = require('node-fetch');

it('test function', () => {
  expect(4).toEqual(4);
});

Package.json

{
  "name": "jest-test",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "scripts": {
    "test": "jest --watchAll"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.15.7",
    "@babel/core": "^7.15.8",
    "@babel/plugin-transform-async-to-generator": "^7.14.5",
    "@babel/preset-env": "^7.15.8",
    "jest": "^27.3.1"
  },
  "dependencies": {
    "node-fetch": "^3.0.0"
  },
  "jest": {
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    }
  }
}

babel.config.cjs

module.exports = {presets: ['@babel/preset-env']}

I'm getting following errors when I run the test using npm test

FAIL  ./script2.test.js
  ● 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. 

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.


    Details:
    
        C:\work\jest-udemy\node_modules\node-fetch\src\index.js:9
        import http from 'http';
        ^^^^^^
    
        SyntaxError: Cannot use import statement outside a module
    
        > 1 | const fetch = require('node-fetch');
        |                   ^

I'm new to JEST, any help is much appreciated. My Node version is 14.17.3 Thanks you.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It seems that one still needs to jump through the hoops to make jest work with ESM.

In package.json change your script to:

"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watchAll"

And in script2.test.js use import:

import fetch from 'node-fetch';

P.S. This was tested with node 14.15.1

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!