Skip to content

Instantly share code, notes, and snippets.

@ThePuscher
Last active April 23, 2022 17:54
Show Gist options
  • Save ThePuscher/466249a2e719d16ba811e61a97215561 to your computer and use it in GitHub Desktop.
Save ThePuscher/466249a2e719d16ba811e61a97215561 to your computer and use it in GitHub Desktop.
jest with ES6 modules

jest with ES6 modules

If you encounter this error when trying to use ES6 modules with jest:

SyntaxError: Cannot use import statement outside a module

Run the tests with:

NODE_OPTIONS=--experimental-vm-modules npx jest

And add this import to your *.test.js files: import { jest } from '@jest/globals'

export const hi = () => {
console.log("hi")
}
import { jest } from '@jest/globals'
import { hi } from "."
it('should say hi', () => {
console.log = jest.fn()
hi()
expect(console.log).toHaveBeenCalledWith("hi")
})
{
"name": "es6_jest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "NODE_OPTIONS=--experimental-vm-modules npx jest"
},
"keywords": ["es6", "jest"],
"author": "github.com/ThePuscher",
"license": "UNLICENSED",
"type": "module",
"devDependencies": {
"jest": "^27.5.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment