Running Jest tests for Typescript ESM modules

typescript, programming, jest, vs code, ESM

It took me 2:30 hours to set this up and document it, it's incredibly tedious 😅

💡 If you're going to create a new npm project, take a look at my npm-package-template

package.json configuration

  • Add jest configuration information to package.json

  • You don't need to use jest.config.js

  • We fix the mandatory import.js rule that comes from ESM with the moduleNameMapper setting

  • We activate esm usage for typescript codes with ^.+\\\\.ts$

// {...
"jest": {
	"preset": "ts-jest",
	"testEnvironment": "node",
	"silent": true,
	"extensionsToTreatAsEsm": [
		".ts"
	],
	"moduleNameMapper": {
		"^(\\\\.{1,2}/.*)\\\\.js$": "$1"
	},
	"transform": {
		"^.+\\\\.ts$": [
			"ts-jest",
			{
				"useESM": true
			}
		]
	}
},
// ...}

launch.json configuration for VSCode

{
	"name": "Jest",
	"type": "node",
	"request": "launch",
	"runtimeArgs": [
		"--experimental-vm-modules", // <<< important
		"${workspaceRoot}/node_modules/.bin/jest",
		"${input:exchange}",
		"-t",
		"${input:testName}",
		"--runInBand"
	],
	"cwd": "${workspaceRoot}",
	"stopOnEntry": false,
	"console": "integratedTerminal",
	"internalConsoleOptions": "neverOpen",
	"sourceMaps": true,
	"windows": {
		"program": "${workspaceFolder}/node_modules/jest/bin/jest"
	},
	"skipFiles": ["<node_internals>/**", "**/node_modules/**"]
},

Error Notes

SyntaxError: Cannot use import statement outside a module

  • We should use node with experimental-vm-modules argument for Jest usage, otherwise we get an error

Plugin Recommendation

References

Jest Typescript with ES Module in node_modules error - Must use import to load ES Module:

ECMAScript Modules · Jest

Typescript, Jest and ECMAScript Modules

Last updated

© 2024 ~ Yunus Emre Ak ~ yEmreAk