Test TypeScript CommonJS
This guide sets up Jest for a TypeScript package without "type": "module". The
ts-cjs preset transforms TypeScript with ts-jest and transforms ESM-only
dependencies to CommonJS with jest-esm-transformer-2.
-
Install Jest, the preset package, and the transformers:
Terminal window pnpm add -D jest @repobuddy/jest ts-jest typescript jest-esm-transformer-2 -
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.js:jest.config.js module.exports = {preset: '@repobuddy/jest/presets/ts-cjs-watch',}ts-watchalso works: it picksts-cjs-watchwhenpackage.jsonhas no"type": "module". -
Make sure
tsconfig.jsoncompiles to CommonJS.ts-jestreads it. -
Put tests in the source folder and name them
<name>.spec.tsor another test file name.
Finished config
Section titled “Finished config”module.exports = { preset: '@repobuddy/jest/presets/ts-cjs-watch',}Verify
Section titled “Verify”pnpm exec jestNo NODE_OPTIONS flag is needed. The ts-cjs fixture in this repository runs 14 suites this way, including one that
imports chalk 6, an ESM-only package.
With ts-jest 29.4.14 the run prints a warning that the ts-jest option isolatedModules is deprecated. The preset
sets that option, so the warning appears even when tsconfig.json sets isolatedModules: true. The tests still run.