14

I have just started learning jest testing and created a sample application to get familiar with jest testing. However, I am getting following error...

enter image description here

Language.js

const calculateTip = (total, percentage) => {
    return total + ((percentage / 100) * total) + 1;
};

export {
    calculateTip,
}

package.json

{
    "dependencies": {
        "express": "^4.18.2"
    },
    "type": "module",
    "main": "src/app.js",
    "scripts": {
        "start": "node src/app.js",
        "test": "cls && env-cmd -f ./envs/test.env jest --watchAll"
    },
    "devDependencies": {
        "env-cmd": "^10.1.0",
        "jest": "^29.2.2",
        "supertest": "^6.3.1"
    }
}

I have tried googling for the solution but no luck so far.

4 Answers 4

9

Jest now ships with experimental support for ECMAScript Modules (ESM):

https://jestjs.io/docs/ecmascript-modules

The simplest way forward is to update your test script to execute node with --experimental-vm-modules e.g.

node --experimental-vm-modules node_modules/jest/bin/jest.js

or to add an environment variable to the test script

NODE_OPTIONS=--experimental-vm-modules npx jest

See the link above for more details.

Sign up to request clarification or add additional context in comments.

1 Comment

The solution is correct. Just to add, in Windows to set NODE_OPTIONS env you may want to use this package: github.com/kentcdodds/cross-env
8

Node.js supports esm syntax only from v16, but jest doesn't support it yet. Therefore, you have 2 choices:

  1. Don't use the esm syntax (import / export)
  2. Add jest-babel with it's config to transpile (convert) esm syntax to cjs one.

1 Comment

Thank you @felixmosh, Although this worked, there are so many depreciation warnings while installing the packages. I had to delete the node_modules directory and install the package before running the npm install command.
3

You can fix it by installing jest-babel and then creating babel.config.cjs in your root directory and pasting the following into it:

//babel.config.cjs
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};
...
//package.json
"type": "module"

//tsconfig.json
...
"target": "esnext", 
"module": "commonjs", 
...

2 Comments

This did not work for me.
You must also make sure that all javascript files in your project end in .js, not .mjs. Otherwise babel won't transpile the file and you'll get errors.
0

Add this to you package.json in scripts:

"test": "cross-env NODE_OPTIONS=--experimental-vm-modules npx jest"

when you run 'npm test', it'll trigger above. 'cross-env' is added so it will run in any shell otherwise not needed in bash.

If you're in bash, then just run 'NODE_OPTIONS=--experimental-vm-modules npx jest'

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.