Search code examples
node.jsecmascript-6jestjses6-modules

Can't use jest in module files for testing in node js


I was trying to use jest for testing my module files and got encountered to error, I looked for online help, tried running test by changing it to a cjs file but wasn't successful. The error I encountered:

 FAIL  tests/sum.test.cjs
  ● 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.

more specifically

  Details:

    <edited_path>\event-management-system\tests\sum.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import sum from '../sum.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/.pnpm/jest-runtime@29.5.0/node_modules/jest-runtime/build/index.js:1495:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.227 s
Ran all test suites.

The files I used to test was sum.js

const sum = (a, b) => {
  return a + b;
};

export default sum;

sum.test.js

import sum from '../sum.js';

describe('sum module', () => {
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
});

Please help me with this specific error

Edit:

I have tried out Changing file types to .mjs files or Use require syntax instead of import. and using .cjs file time for the test file.

package.json

{
  "name": "event-management-system",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "jest": {
    "testMatch": [
      "**/*.test.js"
    ]
  },
  "scripts": {
    "test": "npx jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
  },
  "devDependencies": {
    "jest": "^29.5.0"
  }
}


Solution

  • This is a problem with jest for handling ECMAScript Modules, and the updates are experimental. If you want to use jest for any project where you have described "type": "module" then have look to this documentation.

    Your problem can be fixed by adding a testing script provided below in the package.json file,

    "scripts": {
        "test":"node --experimental-vm-modules node_modules/jest/bin/jest.js"
      },