How to set up jest for es module
In this article, I will show a simple configuration to run jest tests for es module code.
Jest
Jest is a test framework developed by Facebook & often used in applications that use React. It's simple to set up & can be used to test any JS application.
Code
Simple code that uses export es module, src/index.js:
export function a() {
return "function a";
}
Test
Equally simple test, src/index.spec.js:
import { a } from "./index";
describe("function a", () => {
it("should return expected value", () => {
expect(a()).toEqual("function a");
});
});
Configuration
The default Jest configuration works fine with our example code. We need only one configuration file, .babelrc:
{
"env": {
"test": {
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
}
}
Dependencies
We need to install the following depenendcies:
$ npm install --save-dev jest @babel/plugin-transform-modules-commonjs
Execution
With all that in place, we can run our test:
npm run test
> es-module-jest@1.0.0 test /home/marcin/workspace/github/es-module-jest
> jest
PASS src/index.spec.js
function a
✓ should return expected value (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.329 s
Ran all test suites.
Links
Summary
In this article, we have seen a minimalistic setup to run Jest tests for es module code.
About the author
I'm JS developer with 13 years of professional experience. I'm always happy to teach my craft.
Comments
Join the discussionGreat article! Note: I needed to assign "jest" to the "test" script in my package.json file in order for the npm run test script to work.
"scripts": {
"test": "jest"
},
Out of the box, that comes as
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
Also, I can confirm that in Oct '22, I did not need to create the .bablerc config file. I found this article because I was trying to use spyOn and getting the error: SyntaxError: The requested module jest/globals does not provide an export named spyOn. Installing the plugin to transform ES6 (modules) to CommonJS (@babel/plugin-transform-modules-commonjs) fixed this issue, exposing the spyOn function properly for use in my test files.
Thank you so much for sharing all this information!
Hi, its worked! could you explain a little bit about why is the .babelrc config needed?
Good question—I most likely added it based on some troubleshooting and advice I found online. It looks like Jest uses babel, but the configuration it has doesn't support a specific module structure.
It's almost a year ago, so maybe there are newer versions of tools available, and this configuration is not needed anymore. You can remove the plugin line from the .babelrc, and see if it breaks—if not, removing the plugin & the file should be fine too.
Marcin Wosinek guess it is not required. its running fine even when i remove plugin property





