Search code examples
unit-testingecmascript-6jestjses6-modules

Test ES6 modules with Jest


How to test ES6 modules with Jest.


Example:

sum.js

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

export default sum;

sum.test.js

import sum from './sum';

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

Solution

  • [Dec 2023 UPDATE]

    Now you can support ES6 and ESM (ECMAScript modules) natively:

    Step 1: Prevent Jest from trying to transform ESM code to CommonJS, updating your Jest config (package.json example below) with:

    "jest": {
        "transform": {}
    }
    
    

    Step 2: To be able to parse ES modules without an external transformer (e.g., babel), start Node with the --experimental-vm-modules flag. This can be done by changing how Jest is started by the npm "test" script (again inside package.json):

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

    And that's it. :)

    You can even uninstall your transformer packages if you were using them just for the tests.


    [OUTDATED answer, just for historic purposes]

    The only requirement is to config your test environment to Babel, and add the es2015 transform plugin:


    Step 1:

    Add your test environment to .babelrc in the root of your project:

    {
      "env": {
        "test": {
          "plugins": ["@babel/plugin-transform-modules-commonjs"]
        }
      }
    }
    

    Step 2:

    Install the es2015 transform plugin:

    npm install --save-dev @babel/plugin-transform-modules-commonjs
    

    And that's it. Jest will enable compilation from ES modules to CommonJS automatically, without having to inform additional options to your jest property inside package.json.