Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e6e2dc6

Browse files
authored
feat(testing): add projects into jest config (#3766)
* feat(testing): add projects into jest config * chore(testing): update unit tests and fix presets with spreading a default * chore(testing): fix node e2e * chore(testing): review comment changes
1 parent b19d293 commit e6e2dc6

File tree

21 files changed

+378
-52
lines changed

21 files changed

+378
-52
lines changed

e2e/node/src/node.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,8 @@ forEachCli((currentCLIName) => {
355355

356356
expect(stripIndents`${jestConfigContent}`).toEqual(
357357
stripIndents`module.exports = {
358-
name: '${nestlib}',
359-
preset: '../../jest.config.js',
358+
displayName: '${nestlib}',
359+
preset: '../../jest.preset.js',
360360
globals: {
361361
'ts-jest': {
362362
tsConfig: '<rootDir>/tsconfig.spec.json',

packages/angular/src/schematics/storybook-configuration/__snapshots__/configuration.spec.ts.snap

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Array [
88
"/tsconfig.base.json",
99
"/tslint.json",
1010
"/jest.config.js",
11+
"/jest.preset.js",
1112
"/libs/test-ui-lib/README.md",
1213
"/libs/test-ui-lib/tsconfig.lib.json",
1314
"/libs/test-ui-lib/tslint.json",

packages/jest/migrations.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@
3939
"version": "10.2.0",
4040
"description": "Remove deprecated jest builder options",
4141
"factory": "./src/migrations/update-10-2-0/update-10-2-0"
42+
},
43+
"update-projects-property": {
44+
"version": "10.3.0-beta.1",
45+
"description": "Adds all jest projects into the root jest config",
46+
"factory": "./src/migrations/update-10-3-0/update-projects-property"
4247
}
4348
},
4449
"packageJsonUpdates": {

packages/jest/preset/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export = require('./jest-preset');
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export = {
2+
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
3+
resolver: '@nrwl/jest/plugins/resolver',
4+
moduleFileExtensions: ['ts', 'js', 'html'],
5+
coverageReporters: ['html'],
6+
transform: {
7+
'^.+\\.(ts|js|html)$': 'ts-jest',
8+
},
9+
};

packages/jest/src/builders/jest/jest.impl.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,15 @@ import * as path from 'path';
88
import { from, Observable } from 'rxjs';
99
import { map } from 'rxjs/operators';
1010
import { JestBuilderOptions } from './schema';
11+
import { Config } from '@jest/types';
1112

1213
try {
1314
require('dotenv').config();
1415
} catch (e) {
1516
// noop
1617
}
1718

18-
if (process.env.NODE_ENV == null || process.env.NODE_ENV == undefined) {
19+
if (process.env.NODE_ENV === null || process.env.NODE_ENV === undefined) {
1920
(process.env as any).NODE_ENV = 'test';
2021
}
2122

@@ -40,7 +41,8 @@ function run(
4041
);
4142
}
4243

43-
const config: any = {
44+
const config: Config.Argv = {
45+
$0: undefined,
4446
_: [],
4547
config: options.config,
4648
coverage: options.codeCoverage,
@@ -98,14 +100,17 @@ function run(
98100
config.reporters = options.reporters;
99101
}
100102

101-
if (options.coverageReporters && options.coverageReporters.length > 0) {
103+
if (
104+
Array.isArray(options.coverageReporters) &&
105+
options.coverageReporters.length > 0
106+
) {
102107
config.coverageReporters = options.coverageReporters;
103108
}
104109

105110
return from(runCLI(config, [options.jestConfig])).pipe(
106-
map((results) => {
111+
map(({ results }) => {
107112
return {
108-
success: results.results.success,
113+
success: results.success,
109114
};
110115
})
111116
);

packages/jest/src/builders/jest/schema.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export interface JestBuilderOptions extends JsonObject {
2525
colors?: boolean;
2626
reporters?: string[];
2727
verbose?: boolean;
28-
coverageReporters?: string;
28+
coverageReporters?: string[];
2929
coverageDirectory?: string;
3030
testResultsProcessor?: string;
3131
updateSnapshot?: boolean;
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
import { tags } from '@angular-devkit/core';
2+
import { Tree } from '@angular-devkit/schematics';
3+
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
4+
import { serializeJson } from '@nrwl/workspace';
5+
import { createEmptyWorkspace } from '@nrwl/workspace/testing';
6+
import * as path from 'path';
7+
8+
describe('update projects property', () => {
9+
let initialTree: Tree;
10+
let schematicRunner: SchematicTestRunner;
11+
12+
beforeEach(() => {
13+
initialTree = createEmptyWorkspace(Tree.empty());
14+
15+
initialTree.create(
16+
'jest.config.js',
17+
tags.stripIndents`
18+
module.exports = {
19+
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
20+
transform: {
21+
'^.+\\\\.(ts|js|html)$': 'ts-jest',
22+
},
23+
maxWorkers: 2,
24+
};
25+
`
26+
);
27+
28+
initialTree.create(
29+
'apps/products/jest.config.js',
30+
tags.stripIndents`
31+
module.exports = {
32+
name: 'products',
33+
preset: '../../jest.config.js',
34+
coverageDirectory: '../../coverage/apps/products',
35+
snapshotSerializers: [
36+
'jest-preset-angular/build/AngularSnapshotSerializer.js',
37+
'jest-preset-angular/build/HTMLCommentSerializer.js'
38+
],
39+
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
40+
globals: {
41+
'ts-jest': {
42+
tsConfig: '<rootDir>/tsconfig.spec.json',
43+
stringifyContentPathRegex: '\\.(html|svg)$',
44+
astTransformers: [
45+
'jest-preset-angular/build/InlineFilesTransformer',
46+
'jest-preset-angular/build/StripStylesTransformer'
47+
]
48+
}
49+
}
50+
};
51+
`
52+
);
53+
54+
initialTree.overwrite(
55+
'workspace.json',
56+
serializeJson({
57+
version: 1,
58+
projects: {
59+
products: {
60+
root: 'apps/products',
61+
sourceRoot: 'apps/products/src',
62+
architect: {
63+
build: {
64+
builder: '@angular-devkit/build-angular:browser',
65+
},
66+
test: {
67+
builder: '@nrwl/jest:jest',
68+
options: {
69+
jestConfig: 'apps/products/jest.config.js',
70+
tsConfig: 'apps/products/tsconfig.spec.json',
71+
setupFile: 'apps/products/src/test-setup.ts',
72+
passWithNoTests: true,
73+
},
74+
},
75+
},
76+
},
77+
cart: {
78+
root: 'apps/cart',
79+
sourceRoot: 'apps/cart/src',
80+
architect: {
81+
build: {
82+
builder: '@nrwl/web:build',
83+
},
84+
test: {
85+
builder: '@nrwl/jest:jest',
86+
options: {
87+
jestConfig: 'apps/cart/jest.config.js',
88+
passWithNoTests: true,
89+
},
90+
},
91+
},
92+
},
93+
basket: {
94+
root: 'apps/basket',
95+
sourceRoot: 'apps/basket/src',
96+
architect: {
97+
build: {
98+
builder: '@nrwl/web:build',
99+
},
100+
},
101+
},
102+
},
103+
})
104+
);
105+
schematicRunner = new SchematicTestRunner(
106+
'@nrwl/jest',
107+
path.join(__dirname, '../../../migrations.json')
108+
);
109+
});
110+
111+
it('should remove setupFile and tsconfig in test architect from workspace.json', async (done) => {
112+
const result = await schematicRunner
113+
.runSchematicAsync('update-projects-property', {}, initialTree)
114+
.toPromise();
115+
116+
const updatedJestConfig = result.readContent('jest.config.js');
117+
expect(tags.stripIndents`${updatedJestConfig}`).toEqual(tags.stripIndents`
118+
module.exports = {
119+
projects: ['<rootDir>/apps/products', '<rootDir>/apps/cart'],
120+
};
121+
`);
122+
123+
const jestPreset = result.readContent('jest.preset.js');
124+
expect(tags.stripIndents`${jestPreset}`).toEqual(tags.stripIndents`
125+
const nxPreset = require('@nrwl/jest/preset');
126+
module.exports = {
127+
...nxPreset,
128+
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
129+
transform: {
130+
'^.+\\\\.(ts|js|html)$': 'ts-jest',
131+
},
132+
maxWorkers: 2,
133+
};
134+
`);
135+
136+
const projectConfig = result.readContent('apps/products/jest.config.js');
137+
expect(tags.stripIndents`${projectConfig}`).toEqual(tags.stripIndents`
138+
module.exports = {
139+
preset: '../../jest.preset.js',
140+
coverageDirectory: '../../coverage/apps/products',
141+
snapshotSerializers: [
142+
'jest-preset-angular/build/AngularSnapshotSerializer.js',
143+
'jest-preset-angular/build/HTMLCommentSerializer.js',
144+
],
145+
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
146+
globals: {
147+
'ts-jest': {
148+
tsConfig: '<rootDir>/tsconfig.spec.json',
149+
stringifyContentPathRegex: '\\.(html|svg)$',
150+
astTransformers: [
151+
'jest-preset-angular/build/InlineFilesTransformer',
152+
'jest-preset-angular/build/StripStylesTransformer',
153+
],
154+
},
155+
},
156+
displayName: 'products',
157+
};
158+
`);
159+
160+
done();
161+
});
162+
});
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import {
2+
chain,
3+
Rule,
4+
SchematicContext,
5+
Tree,
6+
} from '@angular-devkit/schematics';
7+
import {
8+
formatFiles,
9+
getWorkspace,
10+
insert,
11+
InsertChange,
12+
offsetFromRoot,
13+
serializeJson,
14+
} from '@nrwl/workspace';
15+
import {
16+
addPropertyToJestConfig,
17+
removePropertyFromJestConfig,
18+
} from '../../utils/config/update-config';
19+
import { jestConfigObjectAst } from '../../utils/config/functions';
20+
21+
function updateRootJestConfig(): Rule {
22+
return async (host: Tree, context: SchematicContext) => {
23+
const workspace = await getWorkspace(host);
24+
25+
const rootDirs = [];
26+
for (const [projectName, project] of workspace.projects) {
27+
for (const [, target] of project.targets) {
28+
if (target.builder !== '@nrwl/jest:jest') {
29+
continue;
30+
}
31+
32+
rootDirs.push(`<rootDir>/${project.root}`);
33+
34+
try {
35+
addPropertyToJestConfig(
36+
host,
37+
target.options.jestConfig as string,
38+
'preset',
39+
`${offsetFromRoot(project.root)}jest.preset.js`
40+
);
41+
addPropertyToJestConfig(
42+
host,
43+
target.options.jestConfig as string,
44+
'displayName',
45+
projectName
46+
);
47+
removePropertyFromJestConfig(
48+
host,
49+
target.options.jestConfig as string,
50+
'name'
51+
);
52+
} catch {
53+
context.logger.error(
54+
`Unable to update the jest preset for project ${projectName}. Please manually add "@nrwl/jest/preset" as the preset.`
55+
);
56+
}
57+
}
58+
}
59+
60+
if (rootDirs.length == 0) {
61+
return;
62+
} else {
63+
try {
64+
context.logger.info(`
65+
The root jest.config.js file will be updated to include all references to each individual project's jest config.
66+
A new jest.preset.js file will be created that would have your existing configuration. All projects will now have this preset.
67+
`);
68+
69+
let existingRootConfig = host.read('jest.config.js').toString('utf-8');
70+
71+
existingRootConfig =
72+
"const nxPreset = require('@nrwl/jest/preset'); \n" +
73+
existingRootConfig;
74+
75+
const presetPath = 'jest.preset.js';
76+
77+
host.create(presetPath, existingRootConfig);
78+
const configObject = jestConfigObjectAst(host, presetPath);
79+
insert(host, presetPath, [
80+
new InsertChange(
81+
presetPath,
82+
configObject.getStart() + 1,
83+
'\n...nxPreset,'
84+
),
85+
]);
86+
87+
host.overwrite(
88+
'jest.config.js',
89+
`
90+
module.exports = {
91+
projects: ${serializeJson(rootDirs)}
92+
}
93+
`
94+
);
95+
} catch {
96+
context.logger.error(`
97+
Unable to update the root jest.config.js with projects. Please add the "projects" property to the exported jest config with the following:
98+
${serializeJson(rootDirs)}
99+
`);
100+
}
101+
}
102+
};
103+
}
104+
105+
export default function update(): Rule {
106+
return chain([updateRootJestConfig(), formatFiles()]);
107+
}

packages/jest/src/schematics/init/init.spec.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,7 @@ describe('jest', () => {
1919
expect(resultTree.exists('jest.config.js')).toBeTruthy();
2020
expect(resultTree.readContent('jest.config.js')).toMatchInlineSnapshot(`
2121
"module.exports = {
22-
testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'],
23-
transform: {
24-
'^.+\\\\\\\\.(ts|js|html)$': 'ts-jest'
25-
},
26-
resolver: '@nrwl/jest/plugins/resolver',
27-
moduleFileExtensions: ['ts', 'js', 'html'],
28-
coverageReporters: ['html']
22+
projects: []
2923
};"
3024
`);
3125
});

0 commit comments

Comments
 (0)