Skip to content

Commit

Permalink
fix(testing): pass --js flag to jest generators (#9965)
Browse files Browse the repository at this point in the history
  • Loading branch information
barbados-clemens committed Apr 23, 2022
1 parent 56afad1 commit 8897146
Show file tree
Hide file tree
Showing 38 changed files with 154 additions and 47 deletions.
5 changes: 5 additions & 0 deletions docs/generated/packages/next.json
Expand Up @@ -32,6 +32,11 @@
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"js": {
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript"
}
},
"required": [],
Expand Down
5 changes: 5 additions & 0 deletions docs/generated/packages/node.json
Expand Up @@ -26,6 +26,11 @@
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"js": {
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript"
}
},
"required": [],
Expand Down
5 changes: 5 additions & 0 deletions docs/generated/packages/react-native.json
Expand Up @@ -32,6 +32,11 @@
"type": "string",
"enum": ["detox", "none"],
"default": "detox"
},
"js": {
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript"
}
},
"required": [],
Expand Down
5 changes: 5 additions & 0 deletions docs/generated/packages/react.json
Expand Up @@ -32,6 +32,11 @@
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"js": {
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript"
}
},
"required": [],
Expand Down
10 changes: 6 additions & 4 deletions packages/jest/src/generators/init/init.ts
Expand Up @@ -27,7 +27,8 @@ const schemaDefaults = {
} as const;

function createJestConfig(host: Tree, js: boolean = false) {
if (!host.exists(`jest.config.${js ? 'js' : 'ts'}`)) {
// if the root ts config already exists then don't make a js one or vice versa
if (!host.exists('jest.config.ts') && !host.exists('jest.config.js')) {
host.write(
`jest.config.${js ? 'js' : 'ts'}`,
stripIndents`
Expand All @@ -39,7 +40,7 @@ function createJestConfig(host: Tree, js: boolean = false) {
);
}

if (!host.exists(`jest.preset.${js ? 'js' : 'ts'}`)) {
if (!host.exists('jest.preset.ts') && !host.exists('jest.preset.js')) {
host.write(
`jest.preset.${js ? 'js' : 'ts'}`,
`
Expand All @@ -57,8 +58,7 @@ function updateDependencies(tree: Tree, options: NormalizedSchema) {
const devDeps = {
'@nrwl/jest': nxVersion,
jest: jestVersion,
'@types/jest': jestTypesVersion,
'@types/node': '16.11.7',

// 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
Expand All @@ -67,6 +67,8 @@ function updateDependencies(tree: Tree, options: NormalizedSchema) {

if (!options.js) {
devDeps['ts-node'] = tsNodeVersion;
devDeps['@types/jest'] = jestTypesVersion;
devDeps['@types/node'] = '16.11.7';
}

if (options.compiler === 'babel' || options.babelJest) {
Expand Down
Expand Up @@ -77,3 +77,16 @@ exports[`jestProject should create a jest.config.ts 1`] = `
};
"
`;

exports[`jestProject should use jest.config.js in project config with --js flag 1`] = `
Object {
"executor": "@nrwl/jest:jest",
"options": Object {
"jestConfig": "libs/lib1/jest.config.js",
"passWithNoTests": true,
},
"outputs": Array [
"coverage/libs/lib1",
],
}
`;
25 changes: 25 additions & 0 deletions packages/jest/src/generators/jest-project/jest-project.spec.ts
Expand Up @@ -272,6 +272,31 @@ describe('jestProject', () => {
);
});

it('should use jest.config.js in project config with --js flag', async () => {
await jestProjectGenerator(tree, {
...defaultOptions,
project: 'lib1',
js: true,
} as JestProjectSchema);
expect(tree.exists('libs/lib1/jest.config.js')).toBeTruthy();
expect(
readProjectConfiguration(tree, 'lib1').targets['test']
).toMatchSnapshot();
});

it('should use the jest.preset.ts when preset with --js', async () => {
tree.write('jest.preset.ts', '');
await jestProjectGenerator(tree, {
...defaultOptions,
project: 'lib1',
js: true,
} as JestProjectSchema);
expect(tree.exists('libs/lib1/jest.config.js')).toBeTruthy();
expect(tree.read('libs/lib1/jest.config.js', 'utf-8')).toContain(
"preset: '../../jest.preset.ts',"
);
});

describe('--babelJest', () => {
it('should have globals.ts-jest configured when babelJest is false', async () => {
await jestProjectGenerator(tree, {
Expand Down
Expand Up @@ -4,6 +4,7 @@ import {
readProjectConfiguration,
Tree,
} from '@nrwl/devkit';
import { findRootJestPreset } from '../../../utils/config/find-root-jest-files';
import { join } from 'path';
import { JestProjectSchema } from '../schema';

Expand All @@ -26,7 +27,7 @@ export function createFiles(tree: Tree, options: JestProjectSchema) {
tmpl: '',
...options,
transformer,
ext: options.js && tree.exists('jest.preset.js') ? '.js' : '.ts',
ext: findRootJestPreset(tree) === 'jest.preset.js' ? '.js' : '.ts',
projectRoot: projectConfig.root,
offsetFromRoot: offsetFromRoot(projectConfig.root),
});
Expand Down
@@ -1,22 +1,23 @@
import { findRootJestConfig } from '../../../utils/config/find-root-jest-files';
import { JestProjectSchema } from '../schema';
import { addPropertyToJestConfig } from '../../../utils/config/update-config';
import { readProjectConfiguration, Tree } from '@nrwl/devkit';

function isUsingUtilityFunction(host: Tree, js = false) {
function isUsingUtilityFunction(host: Tree) {
return host
.read(`jest.config.${js ? 'js' : 'ts'}`)
.read(findRootJestConfig(host))
.toString()
.includes('getJestProjects()');
}

export function updateJestConfig(host: Tree, options: JestProjectSchema) {
if (isUsingUtilityFunction(host, options.js)) {
if (isUsingUtilityFunction(host)) {
return;
}
const project = readProjectConfiguration(host, options.project);
addPropertyToJestConfig(
host,
`jest.config.${options.js ? 'js' : 'ts'}`,
findRootJestConfig(host),
'projects',
`<rootDir>/${project.root}`
);
Expand Down
Expand Up @@ -20,7 +20,7 @@ export function updateWorkspace(tree: Tree, options: JestProjectSchema) {
options: {
jestConfig: joinPathFragments(
normalizePath(projectConfig.root),
'jest.config.ts'
`jest.config.${options.js ? 'js' : 'ts'}`
),
passWithNoTests: true,
},
Expand Down
Expand Up @@ -3,7 +3,7 @@
exports[`Jest Migration (v14.0.0) should rename project jest.config.js to jest.config.ts 1`] = `
"module.exports = {
displayName: 'lib-one',
preset: '../../jest.preset.ts',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
Expand All @@ -13,15 +13,15 @@ exports[`Jest Migration (v14.0.0) should rename project jest.config.js to jest.c
'^.+\\\\\\\\.[tj]sx?$': 'ts-jest'
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/lib-one'
coverageDirectory: '../../coverage/libs/lib-one',\\"preset\\": \\"../../jest.preset.ts\\"
};
"
`;

exports[`Jest Migration (v14.0.0) should update jest.config.ts preset to use the jest.preset.ts 1`] = `
"module.exports = {
displayName: 'lib-one',
preset: '../../jest.preset.ts',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
Expand All @@ -31,7 +31,7 @@ exports[`Jest Migration (v14.0.0) should update jest.config.ts preset to use the
'^.+\\\\\\\\.[tj]sx?$': 'ts-jest'
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
coverageDirectory: '../../coverage/libs/lib-one'
coverageDirectory: '../../coverage/libs/lib-one',\\"preset\\": \\"../../jest.preset.ts\\"
};
"
`;
Expand Up @@ -6,29 +6,15 @@ import {
updateProjectConfiguration,
} from '@nrwl/devkit';
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import { jestInitGenerator } from '@nrwl/jest';
import { updateJestConfigExt } from './update-jest-config-ext';
import { libraryGenerator as workspaceLib } from '@nrwl/workspace';

describe('Jest Migration (v14.0.0)', () => {
let tree: Tree;
beforeEach(async () => {
tree = createTreeWithEmptyWorkspace(2);
tree.write(
'jest.config.js',
String.raw`
const { getJestProjects } = require('@nrwl/jest');
module.exports = {
projects: getJestProjects(),
};
`
);
tree.write(
'jest.preset.js',
String.raw`
const nxPreset = require('@nrwl/jest/preset');
module.exports = { ...nxPreset };
`
);
jestInitGenerator(tree, { js: true, skipPackageJson: true });
await workspaceLib(tree, { name: 'lib-one' });
tree.rename('libs/lib-one/jest.config.ts', 'libs/lib-one/jest.config.js');
updateProjectConfiguration(tree, 'lib-one', {
Expand Down
25 changes: 25 additions & 0 deletions packages/jest/src/utils/config/find-root-jest-files.ts
@@ -0,0 +1,25 @@
import { Tree } from '@nrwl/devkit';

export function findRootJestConfig(tree: Tree): string | null {
if (tree.exists('jest.config.js')) {
return 'jest.config.js';
}

if (tree.exists('jest.config.ts')) {
return 'jest.config.ts';
}

return null;
}

export function findRootJestPreset(tree: Tree): string | null {
if (tree.exists('jest.preset.js')) {
return 'jest.preset.js';
}

if (tree.exists('jest.preset.ts')) {
return 'jest.preset.ts';
}

return null;
}
Expand Up @@ -8,7 +8,7 @@ const { exclude: _, ...swcJestConfig } = JSON.parse(

module.exports = {
displayName: '<%= project %>',
preset: '<%= offsetFromRoot %>jest.preset.ts',
preset: '<%= offsetFromRoot %>jest.preset.<%= ext %>',
transform: {
'^.+\\.[tj]s$': ['@swc/jest', swcJestConfig],
},
Expand Down
4 changes: 2 additions & 2 deletions packages/js/src/generators/library/library.spec.ts
Expand Up @@ -570,7 +570,7 @@ describe('lib', () => {
name: 'myLib',
js: true,
});
expect(tree.exists(`libs/my-lib/jest.config.ts`)).toBeTruthy();
expect(tree.exists(`libs/my-lib/jest.config.js`)).toBeTruthy();
expect(tree.exists('libs/my-lib/src/index.js')).toBeTruthy();
expect(tree.exists('libs/my-lib/src/lib/my-lib.js')).toBeTruthy();
expect(tree.exists('libs/my-lib/src/lib/my-lib.spec.js')).toBeTruthy();
Expand Down Expand Up @@ -617,7 +617,7 @@ describe('lib', () => {
directory: 'myDir',
js: true,
});
expect(tree.exists(`libs/my-dir/my-lib/jest.config.ts`)).toBeTruthy();
expect(tree.exists(`libs/my-dir/my-lib/jest.config.js`)).toBeTruthy();
expect(tree.exists('libs/my-dir/my-lib/src/index.js')).toBeTruthy();
expect(
tree.exists('libs/my-dir/my-lib/src/lib/my-dir-my-lib.js')
Expand Down
6 changes: 3 additions & 3 deletions packages/js/src/generators/library/library.ts
Expand Up @@ -14,6 +14,7 @@ import {
updateJson,
} from '@nrwl/devkit';
import { jestProjectGenerator } from '@nrwl/jest';
import { findRootJestPreset } from '@nrwl/jest/src/utils/config/find-root-jest-files';
import { Linter, lintProjectGenerator } from '@nrwl/linter';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import {
Expand Down Expand Up @@ -235,6 +236,7 @@ async function addJest(
options: NormalizedSchema
): Promise<GeneratorCallback> {
return await jestProjectGenerator(tree, {
...options,
project: options.name,
setupFile: 'none',
supportTsx: false,
Expand All @@ -250,12 +252,10 @@ function replaceJestConfig(
options: NormalizedSchema,
filesDir: string
) {
// remove the generated jest config by Jest generator
tree.delete(join(options.projectRoot, 'jest.config.js'));

// replace with JS:SWC specific jest config
generateFiles(tree, filesDir, options.projectRoot, {
tmpl: '',
ext: findRootJestPreset(tree) === 'jest.preset.js' ? 'js' : 'ts',
project: options.name,
offsetFromRoot: offsetFromRoot(options.projectRoot),
projectRoot: options.projectRoot,
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/generators/application/lib/add-jest.ts
Expand Up @@ -8,6 +8,7 @@ export async function addJest(host: Tree, options: NormalizedSchema) {
}

const jestTask = await jestProjectGenerator(host, {
...options,
project: options.projectName,
supportTsx: true,
skipSerializers: true,
Expand Down
Expand Up @@ -6,7 +6,9 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
return;
}

const configPath = `${options.appProjectRoot}/jest.config.ts`;
const configPath = `${options.appProjectRoot}/jest.config.${
options.js ? 'js' : 'ts'
}`;
const originalContent = host.read(configPath, 'utf-8');
const content = originalContent
.replace(
Expand Down
2 changes: 1 addition & 1 deletion packages/next/src/generators/init/init.ts
Expand Up @@ -40,7 +40,7 @@ export async function nextInitGenerator(host: Tree, schema: InitSchema) {
setDefaultCollection(host, '@nrwl/next');

if (!schema.unitTestRunner || schema.unitTestRunner === 'jest') {
const jestTask = jestInitGenerator(host, {});
const jestTask = jestInitGenerator(host, schema);
tasks.push(jestTask);
}
if (!schema.e2eTestRunner || schema.e2eTestRunner === 'cypress') {
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/generators/init/schema.d.ts
Expand Up @@ -2,4 +2,5 @@ export interface InitSchema {
unitTestRunner?: 'jest' | 'none';
e2eTestRunner?: 'cypress' | 'none';
skipFormat?: boolean;
js?: boolean;
}
5 changes: 5 additions & 0 deletions packages/next/src/generators/init/schema.json
Expand Up @@ -22,6 +22,11 @@
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"js": {
"type": "boolean",
"default": false,
"description": "Use JavaScript instead of TypeScript"
}
},
"required": []
Expand Down

1 comment on commit 8897146

@vercel
Copy link

@vercel vercel bot commented on 8897146 Apr 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

nx-dev – ./

nx-dev-nrwl.vercel.app
nx-five.vercel.app
nx.dev
nx-dev-git-master-nrwl.vercel.app

Please sign in to comment.