Jest ES Modules

Jest uses a custom require to import their modules. This means they will need to properly add support for ES Modules. At this time we will still need to use babel-jest to convert ES Modules to work with Jest.

Add mjs to moduleFileExtensions

"moduleFileExtensions": [
	...,
	"mjs"
]

Add babel-jest transform for .mjs files

This overrides the default babel-jest transform for relevant files. If you need .js or other files transformed, make sure to update this regex.

"transform": {
	"^.+\\.mjs$": "babel-jest"
}

Update regex

To handle .mjs and .cjs files.

"testMatch": [
	"**/__tests__/**/*.?(m|c)js?(x)",
	"**/?(*.)(spec|test).?(m|c)js?(x)"
]

@babel/preset-env

@babel/preset-env preset will convert your modules appropriately to your enviroment.

package.json

Jest and Babel configs.

	"jest": {
		"testMatch": [
			"**/__tests__/**/*.?(m|c)js?(x)",
			"**/?(*.)(spec|test).?(m|c)js?(x)"
		],
		"moduleFileExtensions": [
			"js",
			"cjs",
			"mjs"
		],
		"transform": {
			"^.+\\.[t|j]sx?$": "babel-jest", 
			"^.+.m?js$": "babel-jest"
		}
	},
	"babel": {
		"env": {
			"test": {
				"presets": [
					"@babel/preset-env"
				]
			}
		}
	},

What does this let me do?

We can now import ES Modules using .mjs. Currently we need tests to be written in .js, and babel-jest (with babel/preset-env) will help to bridge the gaps. Jest doesn't like .mjs until their loaders and the ES Module standard gets more stability.

objects.test.js

import { create } from './objects.mjs'

test('create with opts', () => {
	expect(create({mass: 1})).toEqual({mass: 1})
})

objects.mjs

export const create = opts => ({...opts})

Note

This is optional if you don't need to convert your .js files over. You may not need this as ES Module support is now available in Node 13.2.

"^.+\\.[t|j]sx?$": "babel-jest",