Test TypeScript ESM
This guide sets up Jest for a TypeScript package that has "type": "module" in package.json. The
ts-esm preset transforms TypeScript with @swc/jest and runs it as native ESM.
-
Install Jest, the preset package, and SWC:
Terminal window pnpm add -D jest @repobuddy/jest @swc/jest @swc/core cross-env -
Add the watch plugins if you use
jest --watch:Terminal window pnpm add -D jest-watch-suspend jest-watch-toggle-config jest-watch-typeahead -
Create
jest.config.mjs:jest.config.mjs export default {preset: '@repobuddy/jest/presets/ts-esm-watch',}Use
ts-esminstead if you skipped step 2.ts-watchalso works: it picksts-esm-watchbecause of"type": "module". -
Run Jest with ESM support. Add scripts to
package.json:{"scripts": {"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest","test:watch": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --watch"}}Without the flag, test files fail with
SyntaxError: Cannot use import statement outside a module. -
Put tests in the source folder (
src,source,ts, orjs) and name them<name>.spec.tsor another test file name. -
Import local files with the
.jsextension, as Node.js ESM requires. The preset maps./foo.jsto./foo.ts:src/foo.spec.ts import { expect, it } from '@jest/globals'import { foo } from './foo.js'it('works', () => {expect(foo).toBe(1)})
Finished config
Section titled “Finished config”export default { preset: '@repobuddy/jest/presets/ts-esm-watch',}Verify
Section titled “Verify”-
List the test files Jest found:
Terminal window pnpm exec cross-env NODE_OPTIONS=--experimental-vm-modules jest --listTests -
Run the tests:
Terminal window pnpm testThe
ts-esmfixture in this repository runs 15 suites this way, including.mts,.cts,.tsx, and.node<major>.tsfiles.
Use ts-jest instead of SWC
Section titled “Use ts-jest instead of SWC”The ESM presets use SWC only. To run TypeScript ESM through ts-jest, compose the config from configs and fields
(see customize a preset).