Test DOM code with jsdom
This guide runs TypeScript tests that touch the DOM. The jsdom presets set testEnvironment: 'jsdom' and their own
test file glob.
-
Install Jest, the preset package, and the jsdom environment:
Terminal window pnpm add -D jest @repobuddy/jest jest-environment-jsdom@repobuddy/jestdoes not declarejest-environment-jsdom, so your package manager will not add it for you. -
Install the transform for your module format:
Terminal window # ESM ("type": "module"): jsdom-ts-esmpnpm add -D @swc/jest @swc/core cross-env# CommonJS: jsdom-ts-cjspnpm add -D ts-jest typescript jest-esm-transformer-2 -
Create the config.
jsdom-tspicks the ESM or CommonJS preset frompackage.jsontype:jest.config.mjs export default {preset: '@repobuddy/jest/presets/jsdom-ts',} -
If the code imports style files, install
identity-obj-proxyand add the CSS mapper:Terminal window pnpm add -D identity-obj-proxyjest.config.mjs import { fields } from '@repobuddy/jest'export default {preset: '@repobuddy/jest/presets/jsdom-ts',moduleNameMapper: fields.knownModuleNameMappers.cssAll,}Jest merges this
moduleNameMapperwith the preset’s. Withidentity-obj-proxy,styles.foois the string'foo'. -
Name tests
<name>.spec.tsor<name>.spec.jsdom.ts.<name>.spec.node.tsfiles do not run in the jsdom presets. See test file names. -
For an ESM package, run Jest with
NODE_OPTIONS=--experimental-vm-modules.
Finished config
Section titled “Finished config”import { fields } from '@repobuddy/jest'
export default { preset: '@repobuddy/jest/presets/jsdom-ts', moduleNameMapper: fields.knownModuleNameMappers.cssAll,}Verify
Section titled “Verify”Write a test that imports a CSS module and uses document:
import styles from './app.module.css'
it('renders', () => { const div = document.createElement('div') div.className = styles.foo document.body.append(div) expect(document.querySelector('.foo')).toBe(div)})This test passed with jsdom-ts-cjs, the cssAll mapper, and Jest 30 in a scratch project. TypeScript needs a
declaration for *.css imports to type-check it.