fix(react): react-router should work with jest out of the box (#30487)

Jest should be compatible with react-router out of the box.

<!-- 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, there are two issues when using `jest` with react-router out
of the box

1. Test files are not included from `tsconfig`
2. While running the test `jsdom` is missing Node's `TextEncoder` and
`TextDecoder` so compilation fails.

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->
Running a test should work without issues when you create a react-router
app with Jest.

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

Fixes #30387
This commit is contained in:
Nicholas Cunningham 2025-03-26 10:44:28 -06:00 committed by GitHub
parent b371512462
commit 1a235d7236
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 201 additions and 52 deletions

View File

@ -9,60 +9,117 @@ import {
} from '@nx/e2e/utils';
describe('React Router Applications', () => {
beforeAll(() => {
newProject({ packages: ['@nx/react'] });
ensureCypressInstallation();
});
afterAll(() => cleanupProject());
it('should generate a react-router application', async () => {
describe('TS paths', () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --no-interactive`
);
beforeAll(() => {
newProject({ packages: ['@nx/react'] });
ensureCypressInstallation();
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --linter=eslint --unit-test-runner=vitest --no-interactive`
);
});
const packageJson = JSON.parse(readFile('package.json'));
expect(packageJson.dependencies['react-router']).toBeDefined();
expect(packageJson.dependencies['@react-router/node']).toBeDefined();
expect(packageJson.dependencies['@react-router/serve']).toBeDefined();
expect(packageJson.dependencies['isbot']).toBeDefined();
afterAll(() => cleanupProject());
checkFilesExist(`${appName}/app/app.tsx`);
checkFilesExist(`${appName}/app/entry.client.tsx`);
checkFilesExist(`${appName}/app/entry.server.tsx`);
checkFilesExist(`${appName}/app/routes.tsx`);
checkFilesExist(`${appName}/react-router.config.ts`);
checkFilesExist(`${appName}/vite.config.ts`);
it('should generate a react-router application', async () => {
const packageJson = JSON.parse(readFile('package.json'));
expect(packageJson.dependencies['react-router']).toBeDefined();
expect(packageJson.dependencies['@react-router/node']).toBeDefined();
expect(packageJson.dependencies['@react-router/serve']).toBeDefined();
expect(packageJson.dependencies['isbot']).toBeDefined();
checkFilesExist(`${appName}/app/app.tsx`);
checkFilesExist(`${appName}/app/entry.client.tsx`);
checkFilesExist(`${appName}/app/entry.server.tsx`);
checkFilesExist(`${appName}/app/routes.tsx`);
checkFilesExist(`${appName}/react-router.config.ts`);
checkFilesExist(`${appName}/vite.config.ts`);
});
it('should be able to build a react-router application', async () => {
const buildResult = runCLI(`build ${appName}`);
expect(buildResult).toContain('Successfully ran target build');
});
it('should be able to lint a react-router application', async () => {
const lintResult = runCLI(`lint ${appName}`);
expect(lintResult).toContain('Successfully ran target lint');
});
it('should be able to test and typecheck a react-router application', async () => {
const typeCheckResult = runCLI(`typecheck ${appName}`);
expect(typeCheckResult).toContain('Successfully ran target typecheck');
});
it('should be able to test and typecheck a react-router application with jest', async () => {
const jestApp = uniq('jestApp');
runCLI(
`generate @nx/react:app ${jestApp} --use-react-router --routing --unit-test-runner=jest --no-interactive`
);
const testResult = runCLI(`test ${jestApp}`);
expect(testResult).toContain('Successfully ran target test');
const typeCheckResult = runCLI(`typecheck ${jestApp}`);
expect(typeCheckResult).toContain('Successfully ran target typecheck');
});
});
it('should be able to build a react-router application', async () => {
describe('TS Solution', () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --no-interactive`
);
beforeAll(() => {
newProject({ preset: 'ts', packages: ['@nx/react'] });
ensureCypressInstallation();
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --linter=eslint --unit-test-runner=vitest --no-interactive`
);
});
const buildResult = runCLI(`build ${appName}`);
expect(buildResult).toContain('Successfully ran target build');
});
afterAll(() => cleanupProject());
it('should be able to lint a react-router application', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --linter=eslint --no-interactive`
);
it('should generate a react-router application', async () => {
const packageJson = JSON.parse(readFile('package.json'));
expect(packageJson.dependencies['react-router']).toBeDefined();
expect(packageJson.dependencies['@react-router/node']).toBeDefined();
expect(packageJson.dependencies['@react-router/serve']).toBeDefined();
expect(packageJson.dependencies['isbot']).toBeDefined();
const buildResult = runCLI(`lint ${appName}`);
expect(buildResult).toContain('Successfully ran target lint');
});
checkFilesExist(`${appName}/app/app.tsx`);
checkFilesExist(`${appName}/app/entry.client.tsx`);
checkFilesExist(`${appName}/app/entry.server.tsx`);
checkFilesExist(`${appName}/app/routes.tsx`);
checkFilesExist(`${appName}/react-router.config.ts`);
checkFilesExist(`${appName}/vite.config.ts`);
});
it('should be able to test a react-router application', async () => {
const appName = uniq('app');
runCLI(
`generate @nx/react:app ${appName} --use-react-router --routing --unit-test-runner=vitest --no-interactive`
);
it('should be able to build a react-router application', async () => {
const buildResult = runCLI(`build ${appName}`);
expect(buildResult).toContain('Successfully ran target build');
});
const buildResult = runCLI(`test ${appName}`);
expect(buildResult).toContain('Successfully ran target test');
it('should be able to lint a react-router application', async () => {
const lintResult = runCLI(`lint ${appName}`);
expect(lintResult).toContain('Successfully ran target lint');
});
it('should be able to test and typecheck a react-router application', async () => {
const testResult = runCLI(`test ${appName}`);
expect(testResult).toContain('Successfully ran target test');
const typeCheckResult = runCLI(`typecheck ${appName}`);
expect(typeCheckResult).toContain('Successfully ran target typecheck');
});
it('should be able to test and typecheck a react-router application with jest', async () => {
const jestApp = uniq('jestApp');
runCLI(
`generate @nx/react:app ${jestApp} --use-react-router --routing --unit-test-runner=jest --no-interactive`
);
const testResult = runCLI(`test ${jestApp}`);
expect(testResult).toContain('Successfully ran target test');
const typeCheckResult = runCLI(`typecheck ${jestApp}`);
expect(typeCheckResult).toContain('Successfully ran target typecheck');
});
});
});

View File

@ -1 +1,7 @@
<% if(setupFile === 'react-native') { %>import '@testing-library/jest-native/extend-expect';<% } %>
<%_ if(setupFile === 'react-router') { _%>
import { TextEncoder, TextDecoder as NodeTextDecoder } from "util";
global.TextEncoder = TextEncoder;
global.TextDecoder = NodeTextDecoder as typeof TextDecoder; // necessary because there is a mismatch between ts type and node type
<%_ } _%>

View File

@ -6,7 +6,12 @@ export interface JestProjectSchema {
* @deprecated use setupFile instead
*/
skipSetupFile?: boolean;
setupFile?: 'angular' | 'web-components' | 'react-native' | 'none';
setupFile?:
| 'angular'
| 'web-components'
| 'react-native'
| 'react-router'
| 'none';
skipSerializers?: boolean;
testEnvironment?: 'node' | 'jsdom' | 'none';
/**

View File

@ -1161,6 +1161,56 @@ describe('app', () => {
expect(packageJson.dependencies['react-router']).toBeDefined();
expect(packageJson.devDependencies['@react-router/dev']).toBeDefined();
});
it('should be configured to work with jest', async () => {
await applicationGenerator(appTree, {
...schema,
skipFormat: false,
useReactRouter: true,
routing: true,
bundler: 'vite',
unitTestRunner: 'jest',
});
const jestConfig = appTree.read('my-app/jest.config.ts').toString();
expect(jestConfig).toContain('@nx/react/plugins/jest');
expect(appTree.read('my-app/tsconfig.spec.json').toString())
.toMatchInlineSnapshot(`
"{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"module": "commonjs",
"moduleResolution": "node10",
"jsx": "react-jsx",
"types": [
"jest",
"node",
"@nx/react/typings/cssmodule.d.ts",
"@nx/react/typings/image.d.ts"
]
},
"files": ["src/test-setup.ts"],
"include": [
"jest.config.ts",
"src/**/*.test.ts",
"src/**/*.spec.ts",
"src/**/*.test.tsx",
"src/**/*.spec.tsx",
"src/**/*.test.js",
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx",
"src/**/*.d.ts",
"test/**/*.spec.tsx",
"test/**/*.spec.ts",
"test/**/*.test.tsx",
"test/**/*.test.ts"
]
}
"
`);
});
});
describe('--directory="." (--root-project)', () => {

View File

@ -235,7 +235,8 @@ export async function applicationGeneratorInternal(
},
options.linter === 'eslint'
? ['eslint.config.js', 'eslint.config.cjs', 'eslint.config.mjs']
: undefined
: undefined,
options.useReactRouter ? 'app' : 'src'
);
sortPackageJsonFields(tree, options.appProjectRoot);

View File

@ -1,4 +1,3 @@
import * as React from "react";
import { NavLink } from "react-router";
export function AppNav() {

View File

@ -1,6 +1,7 @@
import { ensurePackage, GeneratorCallback, Tree } from '@nx/devkit';
import { ensurePackage, GeneratorCallback, Tree, updateJson } from '@nx/devkit';
import { NormalizedSchema } from '../schema';
import { nxVersion } from '../../../utils/versions';
import { join } from 'node:path';
export async function addJest(
host: Tree,
@ -15,14 +16,44 @@ export async function addJest(
nxVersion
);
return await configurationGenerator(host, {
await configurationGenerator(host, {
...options,
project: options.projectName,
supportTsx: true,
skipSerializers: true,
setupFile: 'none',
setupFile: options.useReactRouter ? 'react-router' : 'none',
compiler: options.compiler,
skipFormat: true,
runtimeTsconfigFileName: 'tsconfig.app.json',
});
if (options.useReactRouter) {
updateJson(
host,
join(options.appProjectRoot, 'tsconfig.spec.json'),
(json) => {
json.include = json.include ?? [];
const reactRouterTestGlob = options.js
? [
'test/**/*.spec.jsx',
'test/**/*.spec.js',
'test/**/*.test.jsx',
'test/**/*.test.js',
]
: [
'test/**/*.spec.tsx',
'test/**/*.spec.ts',
'test/**/*.test.tsx',
'test/**/*.test.ts',
];
return {
...json,
include: Array.from(
new Set([...json.include, ...reactRouterTestGlob])
),
};
}
);
}
return () => {};
}