Monday, December 11, 2023
 Popular · Latest · Hot · Upcoming
rated 0 times [  146] [ 2]  / answers: 1 / hits: 11265  / 3 Years ago, mon, july 27, 2020, 12:00:00

I want to use Import/export feature of ES6 modules (since my entire project uses that) with Jest 26.1.0.

I have created a directory for my test cases called testCases/ which contains a math.mjs file. Now I am trying to import this file in math.test.js (for Jest). Whenever I run npm run test, it throws the following error.


import calc from "../src/math.mjs";

SyntaxError: Cannot use import statement outside a module

at Runtime._execModule (node_modules/jest-runtime/build/index.js:1179:56)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.556 s
Ran all test suites.
npm ERR! Test failed. See above for more details.

I even tried changing Jest configuration,as per the documentation and other GitHub issues but no success so far.

Below is my math.mjs testing file

  const calc = (total, tippercent) => {
const tip = total * tippercent;
return total + tip;

export default calc

And this is my math.test.js

import calc from "../src/math.mjs";

test("to calculate tipercent", () => {});

How can we configure Jest to parse .mjs modules?

More From » node.js


I think it would work with following setup:

At root level of your app, jest.config.js:

module.exports = {
testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.(jsx?|js?|tsx?|ts?)$",
transform: {
"^.+\.jsx?$": "babel-jest",
"^.+\.mjs$": "babel-jest",
testPathIgnorePatterns: ["<rootDir>/build/", "<rootDir>/node_modules/"],
moduleFileExtensions: ["js", "jsx", "mjs"]

And babel config babel.config.js:

const presets = [

module.exports = { presets };

And finally your script to run the test in package.json:

"test": "jest --config=jest.config.js",

[#3059] Friday, July 24, 2020, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 113
Total Questions: 100
Total Answers: 115

Location: Egypt
Member since Tue, May 3, 2022
2 Years ago