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.