nx/packages/jest/src/generators/configuration/lib/ensure-dependencies.ts
Nicholas Cunningham 3b3b320ff7
fix(core): add keepExistingVersions to jest option to preserve dependency versions (#30652)
<!-- Please make sure you have read the submission guidelines before
posting an PR -->
<!--
https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr
-->

<!-- Please make sure that your commit message follows our format -->
<!-- Example: `fix(nx): must begin with lowercase` -->

<!-- If this is a particularly complex change or feature addition, you
can request a dedicated Nx release for this pull request branch. Mention
someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they
will confirm if the PR warrants its own release for testing purposes,
and generate it for you if appropriate. -->

## Current Behavior
<!-- This is the behavior we have today -->
Currently, when we use the jest configuration generator it will forcibly
update the jest version if the package already exist.


## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->
Now, the jest version will be preserved unless the option is passed to
update the version.

## Related Issue(s)
<!-- Please link the issue being fixed so it gets closed when this is
merged. -->

Fixes #
2025-05-07 10:01:10 -06:00

55 lines
1.4 KiB
TypeScript

import { addDependenciesToPackageJson, type Tree } from '@nx/devkit';
import {
babelJestVersion,
jestTypesVersion,
jestVersion,
nxVersion,
swcJestVersion,
tsJestVersion,
tslibVersion,
tsNodeVersion,
typesNodeVersion,
} from '../../../utils/versions';
import type { NormalizedJestProjectSchema } from '../schema';
export function ensureDependencies(
tree: Tree,
options: Partial<NormalizedJestProjectSchema>
) {
const dependencies: Record<string, string> = {
tslib: tslibVersion,
};
const devDeps: Record<string, string> = {
// because the default jest-preset uses ts-jest,
// jest will throw an error if it's not installed
// even if not using it in overriding transformers
'ts-jest': tsJestVersion,
};
if (options.testEnvironment !== 'none') {
devDeps[`jest-environment-${options.testEnvironment}`] = jestVersion;
}
if (!options.js) {
devDeps['ts-node'] = tsNodeVersion;
devDeps['@types/jest'] = jestTypesVersion;
devDeps['@types/node'] = typesNodeVersion;
}
if (options.compiler === 'babel' || options.babelJest) {
devDeps['babel-jest'] = babelJestVersion;
// in some cases @nx/js will not already be present i.e. node only projects
devDeps['@nx/js'] = nxVersion;
} else if (options.compiler === 'swc') {
devDeps['@swc/jest'] = swcJestVersion;
}
return addDependenciesToPackageJson(
tree,
dependencies,
devDeps,
undefined,
options.keepExistingVersions
);
}