Skip to content

Commit

Permalink
feat(testing): move jest config to .ts
Browse files Browse the repository at this point in the history
move jest config and preset to ts files

ISSUES CLOSED: #8344
  • Loading branch information
barbados-clemens committed Apr 19, 2022
1 parent 4f1c14c commit abb0a0a
Show file tree
Hide file tree
Showing 14 changed files with 271 additions and 21 deletions.
6 changes: 6 additions & 0 deletions packages/jest/migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@
"cli": "nx",
"description": "Create a root babel config file if it doesn't exist and using babel-jest in jest.config.js and add @nrwl/web as needed",
"factory": "./src/migrations/update-13-4-4/add-missing-root-babel-config"
},
"update-jest-config-extensions": {
"version": "14.0.0-beta.0",
"cli": "nx",
"description": "Update move jest config files to .ts files.",
"factory": "./src/migrations/update-14-0-0/update-jest-config-ext"
}
},
"packageJsonUpdates": {
Expand Down
8 changes: 4 additions & 4 deletions packages/jest/src/generators/init/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ const schemaDefaults = {
} as const;

function createJestConfig(host: Tree) {
if (!host.exists('jest.config.js')) {
if (!host.exists('jest.config.ts')) {
host.write(
'jest.config.js',
'jest.config.ts',
stripIndents`
const { getJestProjects } = require('@nrwl/jest');
Expand All @@ -37,9 +37,9 @@ function createJestConfig(host: Tree) {
);
}

if (!host.exists('jest.preset.js')) {
if (!host.exists('jest.preset.ts')) {
host.write(
'jest.preset.js',
'jest.preset.ts',
`
const nxPreset = require('@nrwl/jest/preset');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
displayName: '<%= project %>',
preset: '<%= offsetFromRoot %>jest.preset.js',
preset: '<%= offsetFromRoot %>jest.preset.ts',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
globals: {
'ts-jest': {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = {
displayName: '<%= project %>',
preset: '<%= offsetFromRoot %>jest.preset.js',<% if(setupFile !== 'none') { %>
preset: '<%= offsetFromRoot %>jest.preset.ts',<% if(setupFile !== 'none') { %>
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],<% } %><% if (transformer === 'ts-jest') { %>
globals: {
'ts-jest': {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { addPropertyToJestConfig } from '../../../utils/config/update-config';
import { readProjectConfiguration, Tree } from '@nrwl/devkit';

function isUsingUtilityFunction(host: Tree) {
return host.read('jest.config.js').toString().includes('getJestProjects()');
return host.read('jest.config.ts').toString().includes('getJestProjects()');
}

export function updateJestConfig(host: Tree, options: JestProjectSchema) {
Expand All @@ -13,7 +13,7 @@ export function updateJestConfig(host: Tree, options: JestProjectSchema) {
const project = readProjectConfiguration(host, options.project);
addPropertyToJestConfig(
host,
'jest.config.js',
'jest.config.ts',
'projects',
`<rootDir>/${project.root}`
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function updateWorkspace(tree: Tree, options: JestProjectSchema) {
options: {
jestConfig: joinPathFragments(
normalizePath(projectConfig.root),
'jest.config.js'
'jest.config.ts'
),
passWithNoTests: true,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

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',
}
},
transform: {
'^.+\\\\\\\\.[tj]s$': 'ts-jest'
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/libs/lib-one'
};
"
`;

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',
}
},
transform: {
'^.+\\\\\\\\.[tj]s$': 'ts-jest'
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/libs/lib-one'
};
"
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import {
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import { libraryGenerator } from '@nrwl/js';
import { updateJestConfigExt } from './update-jest-config-ext';

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 };
`
);
await libraryGenerator(tree, { name: 'lib-one' });
tree.rename('libs/lib-one/jest.config.ts', 'libs/lib-one/jest.config.js');
updateProjectConfiguration(tree, 'lib-one', {
...readProjectConfiguration(tree, 'lib-one'),
targets: {
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-one/jest.config.js',
passWithNoTests: true,
},
},
},
});
});

it('should rename project jest.config.js to jest.config.ts', async () => {
await updateJestConfigExt(tree);
expect(tree.exists('libs/lib-one/jest.config.ts')).toBeTruthy();
expect(tree.read('libs/lib-one/jest.config.ts', 'utf-8')).toMatchSnapshot();
});

it('should rename root jest files', async () => {
await updateJestConfigExt(tree);
expect(tree.exists('jest.config.ts')).toBeTruthy();
expect(tree.exists('jest.preset.ts')).toBeTruthy();
});

it('should update jest.config.ts preset to use the jest.preset.ts', async () => {
tree.rename('libs/lib-one/jest.config.js', 'libs/lib-one/jest.config.ts');
const projectConfig = readProjectConfiguration(tree, 'lib-one');
updateProjectConfiguration(tree, 'lib-one', {
...projectConfig,
targets: {
test: {
...projectConfig.targets.test,
options: {
jestConfig: 'libs/lib-one/jest.config.ts',
passWithNoTests: true,
},
},
},
});
expect(tree.exists('libs/lib-one/jest.config.ts')).toBeTruthy();
await updateJestConfigExt(tree);
expect(tree.exists('libs/lib-one/jest.config.ts')).toBeTruthy();
expect(tree.read('libs/lib-one/jest.config.ts', 'utf-8')).toMatchSnapshot();
});

it('should only update js/ts files', async () => {
tree.rename('libs/lib-one/jest.config.js', 'libs/lib-one/jest.config.ts');
updateProjectConfiguration(tree, 'lib-one', {
...readProjectConfiguration(tree, 'lib-one'),
targets: {
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-one/jest.config.ts',
passWithNoTests: true,
},
},
},
});

await libraryGenerator(tree, { name: 'lib-two' });
tree.delete('libs/lib-two/jest.config.ts'); // lib generator creates a ts file
tree.write('libs/lib-two/jest.config.json', '{}');
updateProjectConfiguration(tree, 'lib-two', {
...readProjectConfiguration(tree, 'lib-two'),
targets: {
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-two/jest.config.json',
passWithNoTests: true,
},
},
},
});
await libraryGenerator(tree, { name: 'lib-three' });

expect(tree.exists('libs/lib-one/jest.config.ts')).toBeTruthy();
await updateJestConfigExt(tree);
expect(tree.exists('libs/lib-one/jest.config.ts')).toBeTruthy();
expect(tree.exists('libs/lib-two/jest.config.ts')).toBeFalsy();
expect(tree.exists('libs/lib-two/jest.config.json')).toBeTruthy();
expect(tree.exists('libs/lib-three/jest.config.ts')).toBeTruthy();
});

it('should not throw error if file does not exit', async () => {
tree.delete('libs/lib-one/jest.config.js');
await updateJestConfigExt(tree);
expect(tree.exists('libs/lib-one/jest.config.ts')).toBeFalsy();
expect(tree.exists('libs/lib-one/jest.config.js')).toBeFalsy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
formatFiles,
logger,
offsetFromRoot,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';
import { jestConfigObject } from '../../utils/config/functions';
import { dirname, extname, join } from 'path';
import {
removePropertyFromJestConfig,
addPropertyToJestConfig,
} from '../../utils/config/update-config';
import { JestExecutorOptions } from '../../executors/jest/schema';
import { forEachExecutorOptions } from '@nrwl/workspace/src/utilities/executor-options-utils';

const allowedExt = ['.ts', '.js'];

export async function updateJestConfigExt(tree: Tree) {
let isRootPresetUpdated = false;
if (tree.exists('jest.config.js')) {
tree.rename('jest.config.js', 'jest.config.ts');
} else {
logger.debug(`Did not find root jest.config.js to rename, skipping`);
}

if (tree.exists('jest.preset.js')) {
isRootPresetUpdated = true;
tree.rename('jest.preset.js', 'jest.preset.ts');
} else {
logger.debug(`Did not find jest.preset.js to rename, skipping`);
}

forEachExecutorOptions<JestExecutorOptions>(
tree,
'@nrwl/jest:jest',
(options, projectName, target, configuration) => {
const configExt = extname(options.jestConfig);
console.log(`configExt: ${configExt}`);
if (!tree.exists(options.jestConfig) || !allowedExt.includes(configExt)) {
logger.debug(
`unable to update file because it doesn't exist or is not a js or ts file. Config: ${
options.jestConfig
}. Exists?: ${tree.exists(options.jestConfig)}`
);
return;
}

const oldConfig = jestConfigObject(tree, options.jestConfig);

// if using the root preset and the root preset was updated to ts file.
// then update the jest config
if (isRootPresetUpdated && oldConfig.preset.endsWith('jest.preset.js')) {
removePropertyFromJestConfig(tree, options.jestConfig, 'preset');
addPropertyToJestConfig(
tree,
options.jestConfig,
'preset',
join(offsetFromRoot(dirname(options.jestConfig)), 'jest.preset.ts'),
{ valueAsString: false }
);
} else {
logger.debug(
isRootPresetUpdated
? `Existing preset for project ${projectName} did not end with 'jest.preset.js' there for not updating it. Actual preset: ${oldConfig.preset}`
: `Did not update root preset; therefore, not updating ${projectName} jest config preset @ ${options.jestConfig}`
);
}
const newJestConfigPath = options.jestConfig.replace('.js', '.ts');

tree.rename(options.jestConfig, newJestConfigPath);
const projectConfig = readProjectConfiguration(tree, projectName);

projectConfig.targets[target].options.jestConfig = newJestConfigPath;
updateProjectConfiguration(tree, projectName, projectConfig);
}
);
await formatFiles(tree);
}

export default updateJestConfigExt;
2 changes: 1 addition & 1 deletion packages/jest/src/utils/config/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export function jestConfigObjectAst(
fileContent: string
): ts.ObjectLiteralExpression {
const sourceFile = ts.createSourceFile(
'jest.config.js',
'jest.config.ts',
fileContent,
ts.ScriptTarget.Latest,
true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
return;
}

const configPath = `${options.appProjectRoot}/jest.config.js`;
const configPath = `${options.appProjectRoot}/jest.config.ts`;
const originalContent = host.read(configPath, 'utf-8');
const content = originalContent
.replace(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function updateJestConfig(host: Tree, options: NormalizedSchema) {
return json;
});

const configPath = `${options.appProjectRoot}/jest.config.js`;
const configPath = `${options.appProjectRoot}/jest.config.ts`;
const originalContent = host.read(configPath, 'utf-8');
const content = updateJestConfigContent(originalContent);
host.write(configPath, content);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export function updateJestConfig(
) {
const jestConfigPath = path.join(
schema.relativeToRootDestination,
'jest.config.js'
'jest.config.ts'
);

if (tree.exists(jestConfigPath)) {
Expand Down

0 comments on commit abb0a0a

Please sign in to comment.