Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: node.js SyntaxError: Cannot use import statement outside a module

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.

like image 232
MrSingh Avatar asked Feb 06 '26 17:02

MrSingh


2 Answers

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.

like image 118
Callum Avatar answered Feb 09 '26 10:02

Callum


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.
like image 43
felixmosh Avatar answered Feb 09 '26 11:02

felixmosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!