import { ensurePackage, joinPathFragments, readJson, Tree, updateJson, GeneratorCallback, } from '@nx/devkit'; import { nxVersion } from '../../../utils/versions'; import { NormalizedSchema } from './normalize-options'; export async function addJest( host: Tree, options: NormalizedSchema ): Promise { if (options.unitTestRunner !== 'jest') { return () => {}; } const { configurationGenerator } = ensurePackage( '@nx/jest', nxVersion ); const jestTask = await configurationGenerator(host, { ...options, project: options.projectName, supportTsx: true, skipSerializers: true, setupFile: 'none', // The generated config is replaced by updateJestConfig, so this only decides // which transformer package gets installed; 'tsc' installs none. compiler: 'tsc', skipFormat: true, runtimeTsconfigFileName: 'tsconfig.json', }); const tsConfigSpecJson = readJson( host, joinPathFragments(options.appProjectRoot, 'tsconfig.spec.json') ); updateJson( host, joinPathFragments(options.appProjectRoot, 'tsconfig.json'), (json) => { json.compilerOptions ??= {}; json.compilerOptions.types ??= []; json.compilerOptions.types.push( ...(tsConfigSpecJson?.compilerOptions?.types ?? []) ); return json; } ); updateJson( host, joinPathFragments(options.appProjectRoot, 'tsconfig.spec.json'), (json) => { json.compilerOptions.jsx = 'react'; // Override exclude so typed linting doesn't fail on jest.config.ts and jest.config.cts. if (options.enableTypedLinting) { const tsConfig = readJson( host, joinPathFragments(options.appProjectRoot, 'tsconfig.json') ); json.exclude = tsConfig.exclude.filter( (e) => e !== 'jest.config.ts' && e !== 'jest.config.cts' ); } return json; } ); return jestTask; }