# Running Jest tests for Typescript ESM modules

> 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](https://github.com/yemreak/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$`

```javascript
// {...
"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

```javascript
{
	"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

{% embed url="<https://marketplace.visualstudio.com/items?itemName=vespa-dev-works.jestRunIt>" %}

## References

[Jest Typescript with ES Module in node\_modules error - Must use import to load ES Module:](https://stackoverflow.com/a/69117363/9770490)

[ECMAScript Modules · Jest](https://jestjs.io/docs/ecmascript-modules)

[Typescript, Jest and ECMAScript Modules](https://gist.github.com/danpetitt/37f5c966886f54e457ece4b08d66e404?permalink_comment_id=4710758#gistcomment-4710758)
