Skip to content

Commit

Permalink
feat(testing): update test generators to exclude test files from the …
Browse files Browse the repository at this point in the history
…runtime tsconfig file (#27991)

<!-- 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 -->

## Expected Behavior
<!-- This is the behavior we should expect with the changes in this PR
-->

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

Fixes #
  • Loading branch information
leosvelperez authored Sep 23, 2024
1 parent c92528f commit d454f25
Show file tree
Hide file tree
Showing 18 changed files with 185 additions and 93 deletions.
4 changes: 4 additions & 0 deletions docs/generated/packages/jest/generators/configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript for config files"
},
"runtimeTsconfigFileName": {
"type": "string",
"description": "The name of the project's tsconfig file that includes the runtime source files. If not provided, it will default to `tsconfig.lib.json` for libraries and `tsconfig.app.json` for applications."
}
},
"required": [],
Expand Down
4 changes: 4 additions & 0 deletions docs/generated/packages/vite/generators/vitest.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@
"description": "The vitest environment to use. See https://vitest.dev/config/#environment.",
"type": "string",
"enum": ["node", "jsdom", "happy-dom", "edge-runtime"]
},
"runtimeTsconfigFileName": {
"type": "string",
"description": "The name of the project's tsconfig file that includes the runtime source files. If not provided, it will default to `tsconfig.lib.json` for libraries and `tsconfig.app.json` for applications."
}
},
"required": ["project"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ describe('app', () => {
const tsConfigApp = readJson(appTree, 'my-node-app/tsconfig.app.json');
expect(tsConfigApp.include).toEqual(['src/**/*.ts', 'src/**/*.js']);
expect(tsConfigApp.exclude).toEqual([
'jest.config.ts',
'jest.config.js',
'src/**/*.spec.ts',
'src/**/*.test.ts',
'src/**/*.spec.js',
Expand Down
58 changes: 50 additions & 8 deletions packages/jest/src/generators/configuration/lib/update-tsconfig.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import { join } from 'path';
import { NormalizedJestProjectSchema } from '../schema';
import { readProjectConfiguration, Tree, updateJson } from '@nx/devkit';
import {
joinPathFragments,
logger,
readProjectConfiguration,
updateJson,
type Tree,
} from '@nx/devkit';
import type { NormalizedJestProjectSchema } from '../schema';

export function updateTsConfig(
host: Tree,
options: NormalizedJestProjectSchema
) {
const projectConfig = readProjectConfiguration(host, options.project);
if (!host.exists(join(projectConfig.root, 'tsconfig.json'))) {
const { root, projectType } = readProjectConfiguration(host, options.project);
if (!host.exists(joinPathFragments(root, 'tsconfig.json'))) {
throw new Error(
`Expected ${join(
projectConfig.root,
`Expected ${joinPathFragments(
root,
'tsconfig.json'
)} to exist. Please create one.`
);
}
updateJson(host, join(projectConfig.root, 'tsconfig.json'), (json) => {
updateJson(host, joinPathFragments(root, 'tsconfig.json'), (json) => {
if (
json.references &&
!json.references.some((r) => r.path === './tsconfig.spec.json')
Expand All @@ -26,4 +31,41 @@ export function updateTsConfig(
}
return json;
});

// fall-back runtime tsconfig file path in case the user didn't provide one
let runtimeTsconfigPath = joinPathFragments(
root,
projectType === 'application' ? 'tsconfig.app.json' : 'tsconfig.lib.json'
);
if (options.runtimeTsconfigFileName) {
runtimeTsconfigPath = joinPathFragments(
root,
options.runtimeTsconfigFileName
);
if (!host.exists(runtimeTsconfigPath)) {
// the user provided a runtimeTsconfigFileName that doesn't exist, so we throw an error
throw new Error(
`Cannot find the provided runtimeTsConfigFileName ("${options.runtimeTsconfigFileName}") at the project root "${root}".`
);
}
}

if (host.exists(runtimeTsconfigPath)) {
updateJson(host, runtimeTsconfigPath, (json) => {
const uniqueExclude = new Set([
...(json.exclude || []),
options.js ? 'jest.config.js' : 'jest.config.ts',
'src/**/*.spec.ts',
'src/**/*.test.ts',
...(options.js ? ['src/**/*.spec.js', 'src/**/*.test.js'] : []),
]);
json.exclude = [...uniqueExclude];
return json;
});
} else {
logger.warn(
`Couldn't find a runtime tsconfig file at ${runtimeTsconfigPath} to exclude the test files from. ` +
`If you're using a different filename for your runtime tsconfig, please provide it with the '--runtimeTsconfigFileName' flag.`
);
}
}
1 change: 1 addition & 0 deletions packages/jest/src/generators/configuration/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface JestProjectSchema {
compiler?: 'tsc' | 'babel' | 'swc';
skipPackageJson?: boolean;
js?: boolean;
runtimeTsconfigFileName?: string;

/**
* @internal
Expand Down
4 changes: 4 additions & 0 deletions packages/jest/src/generators/configuration/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript for config files"
},
"runtimeTsconfigFileName": {
"type": "string",
"description": "The name of the project's tsconfig file that includes the runtime source files. If not provided, it will default to `tsconfig.lib.json` for libraries and `tsconfig.app.json` for applications."
}
},
"required": []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,5 @@
"declaration": true,
"types": ["node"]
},
"include": ["src/**/*.ts"<% if (js) { %>, "src/**/*.js"<% } %>],
"exclude": [
<% if (hasUnitTestRunner && unitTestRunner === 'jest') { %>"jest.config.ts",
<% } else if (hasUnitTestRunner) { %>"vite.config.ts",
<% } %>"src/**/*.spec.ts", "src/**/*.test.ts"<% if (js) { %>, "src/**/*.spec.js", "src/**/*.test.js"<% } %>
]
"include": ["src/**/*.ts"<% if (js) { %>, "src/**/*.js"<% } %>]
}
2 changes: 2 additions & 0 deletions packages/js/src/generators/library/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ export async function libraryGeneratorInternal(
coverageProvider: 'v8',
skipFormat: true,
testEnvironment: options.testEnvironment,
runtimeTsconfigFileName: 'tsconfig.lib.json',
});
tasks.push(vitestTask);
createOrEditViteConfig(
Expand Down Expand Up @@ -601,6 +602,7 @@ async function addJest(
: options.bundler === 'rollup'
? 'swc'
: undefined,
runtimeTsconfigFileName: 'tsconfig.lib.json',
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ describe('app', () => {
const tsConfigApp = readJson(tree, 'my-node-app/tsconfig.app.json');
expect(tsConfigApp.include).toEqual(['src/**/*.ts', 'src/**/*.js']);
expect(tsConfigApp.exclude).toEqual([
'jest.config.ts',
'jest.config.js',
'src/**/*.spec.ts',
'src/**/*.test.ts',
'src/**/*.spec.js',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,5 @@
"module": "commonjs",
"types": ["node"]
},
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,38 @@ exports[`@nx/vite:configuration js library with --bundler=vite should add build
"types": ["node", "vite/client"]
},
"include": ["src/**/*.ts"],
"exclude": ["vite.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
"exclude": [
"vite.config.ts",
"vitest.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"
]
}
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect unitTestRunner if passed 1`] = `
exports[`@nx/vite:configuration js library with --bundler=vite should respect provided unitTestRunner="jest" 1`] = `
"# my-lib
This library was generated with [Nx](https://nx.dev).
## Building
Run \`nx build my-lib\` to build the library.
## Running unit tests
Run \`nx test my-lib\` to execute the unit tests via [Jest](https://jestjs.io).
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect unitTestRunner if passed 2`] = `
exports[`@nx/vite:configuration js library with --bundler=vite should respect provided unitTestRunner="jest" 2`] = `
"{
"extends": "./tsconfig.json",
"compilerOptions": {
Expand All @@ -115,53 +130,48 @@ exports[`@nx/vite:configuration js library with --bundler=vite should respect un
"types": ["node", "vite/client"]
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
}
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect unitTestRunner if passed 3`] = `
exports[`@nx/vite:configuration js library with --bundler=vite should respect provided unitTestRunner="jest" 3`] = `
"export default {
displayName: 'my-lib',
preset: '../jest.preset.js',
transform: {
'^.+\\\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../coverage/my-lib',
};
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect provided unitTestRunner="none" 1`] = `
"# my-lib
This library was generated with [Nx](https://nx.dev).
## Building
Run \`nx build my-lib\` to build the library.
## Running unit tests
Run \`nx test my-lib\` to execute the unit tests via [Jest](https://jestjs.io).
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect unitTestRunner if passed 4`] = `
exports[`@nx/vite:configuration js library with --bundler=vite should respect provided unitTestRunner="none" 2`] = `
"{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../dist/out-tsc",
"declaration": true,
"types": ["node", "vite/client"]
},
"include": ["src/**/*.ts"],
"exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"]
"include": ["src/**/*.ts"]
}
"
`;

exports[`@nx/vite:configuration js library with --bundler=vite should respect unitTestRunner if passed 5`] = `
"export default {
displayName: 'my-lib',
preset: '../jest.preset.js',
transform: {
'^.+\\\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../coverage/my-lib',
};
"
`;

exports[`@nx/vite:configuration library mode should add config for building library 1`] = `
"/// <reference types='vitest' />
import { defineConfig } from 'vite';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ describe('@nx/vite:configuration', () => {
${'none'} | ${undefined}
${'jest'} | ${'my-lib/jest.config.ts'}
`(
'should respect unitTestRunner if passed',
'should respect provided unitTestRunner="$unitTestRunner"',
async ({ unitTestRunner, configPath }) => {
await jsLibraryGenerator(tree, {
...defaultOptions,
Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/generators/vitest/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export interface VitestGeneratorSchema {
skipFormat?: boolean;
testEnvironment?: 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string;
addPlugin?: boolean;
runtimeTsconfigFileName?: string;
}
4 changes: 4 additions & 0 deletions packages/vite/src/generators/vitest/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
"description": "The vitest environment to use. See https://vitest.dev/config/#environment.",
"type": "string",
"enum": ["node", "jsdom", "happy-dom", "edge-runtime"]
},
"runtimeTsconfigFileName": {
"type": "string",
"description": "The name of the project's tsconfig file that includes the runtime source files. If not provided, it will default to `tsconfig.lib.json` for libraries and `tsconfig.app.json` for applications."
}
},
"required": ["project"]
Expand Down
Loading

0 comments on commit d454f25

Please sign in to comment.