Skip to content

Commit

Permalink
fix(testing): Create root babel config if one isn't present (#7816)
Browse files Browse the repository at this point in the history
* fix(testing): create root babel config for babel-jest option

when creating a jest project with babel-jest a root babel.config.json file will be create if one

doesn't exist and babel deps install for allowing jest tests to run successfully

ISSUES CLOSED: #6782

* feat(testing): add migration for missing root babel config
  • Loading branch information
barbados-clemens authored Jan 7, 2022
1 parent b3fb9ee commit baf44ad
Show file tree
Hide file tree
Showing 7 changed files with 220 additions and 7 deletions.
12 changes: 12 additions & 0 deletions e2e/jest/src/jest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,16 @@ describe('Jest', () => {
); // text
expect(result.stdout).toContain('Coverage summary'); // text-summary
}, 90000);

it('should be able to test node lib with babel-jest', async () => {
const libName = uniq('babel-test-lib');
runCLI(
`generate @nrwl/node:lib ${libName} --buildable --importPath=@some-org/babel-test --publishable --babelJest`
);

const cliResults = await runCLIAsync(`test ${libName}`);
expect(cliResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
});
});
6 changes: 6 additions & 0 deletions packages/jest/migrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@
"cli": "nx",
"description": "Support .test. file names in tsconfigs",
"factory": "./src/migrations/update-13-1-2/update-tsconfigs-for-tests"
},
"add-missing-root-babel-config": {
"version": "13.4.4-beta.0",
"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"
}
},
"packageJsonUpdates": {
Expand Down
14 changes: 9 additions & 5 deletions packages/jest/src/generators/init/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,19 @@ function updateDependencies(tree: Tree, options: NormalizedSchema) {
'@nrwl/jest': nxVersion,
jest: jestVersion,
'@types/jest': jestTypesVersion,
// 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
'ts-jest': tsJestVersion,
};

// TODO: revert to @swc/jest when https://github.com/swc-project/cli/issues/20 is addressed
// } else if (options.compiler === 'swc') {
// devDeps['@swc/jest'] = swcJestVersion;
if (options.compiler === 'babel' || options.babelJest) {
devDeps['babel-jest'] = babelJestVersion;
} else {
devDeps['ts-jest'] = tsJestVersion;
// in some cases @nrwl/web will not already be present i.e. node only projects
devDeps['@nrwl/web'] = nxVersion;
// TODO: revert to @swc/jest when https://github.com/swc-project/cli/issues/20 is addressed
// } else if (options.compiler === 'swc') {
// devDeps['@swc/jest'] = swcJestVersion;
}

return addDependenciesToPackageJson(tree, dependencies, devDeps);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ describe('jestProject', () => {
expect(tree.exists('libs/lib1/tsconfig.spec.json')).toBeTruthy();
});

it('should generate files w/babel-jest', async () => {
await jestProjectGenerator(tree, {
...defaultOptions,
project: 'lib1',
babelJest: true,
} as JestProjectSchema);
expect(tree.exists('babel.config.json')).toBeTruthy();
});

it('should alter workspace.json', async () => {
await jestProjectGenerator(tree, {
...defaultOptions,
Expand Down
13 changes: 11 additions & 2 deletions packages/jest/src/generators/jest-project/lib/create-files.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { JestProjectSchema } from '../schema';
import {
Tree,
offsetFromRoot,
generateFiles,
offsetFromRoot,
readProjectConfiguration,
Tree,
} from '@nrwl/devkit';
import { join } from 'path';

Expand Down Expand Up @@ -33,4 +33,13 @@ export function createFiles(tree: Tree, options: JestProjectSchema) {
if (options.setupFile === 'none') {
tree.delete(join(projectConfig.root, './src/test-setup.ts'));
}

if (options.babelJest && !tree.exists('babel.config.json')) {
tree.write(
'babel.config.json',
JSON.stringify({
babelrcRoots: ['*'],
})
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { addProjectConfiguration, readJson, Tree } from '@nrwl/devkit';
import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing';
import update from './add-missing-root-babel-config';

describe('Jest Migration (v13.4.4)', () => {
let tree: Tree;
beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
tree.write(
'package.json',
JSON.stringify({
name: 'test',
version: '',
description: '',
devDependencies: {},
})
);
tree.write(
'libs/lib-one/jest.config.js',
String.raw`module.exports = {
transform: {
'^.+\\\\.[tj]sx?$': 'babel-jest',
}
}`
);

addProjectConfiguration(tree, 'lib-one', {
root: 'libs/lib-one',
sourceRoot: 'libs/lib-one/src',
projectType: 'library',
targets: {
build: {
executor: '@nrwl/web:build',
},
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-one/jest.config.js',
passWithNoTests: true,
},
},
},
});

addProjectConfiguration(tree, 'lib-two', {
root: 'libs/lib-two',
sourceRoot: 'libs/lib-two/src',
projectType: 'library',
targets: {
build: {
executor: '@nrwl/web:build',
},
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-two/jest.config.js',
passWithNoTests: true,
},
},
},
});
});

it('should create root babel.config.json and install @nrwl/web', async () => {
await update(tree);
expect(tree.exists('babel.config.json')).toBeTruthy();
const packageJson = readJson(tree, 'package.json');
expect(packageJson.devDependencies['@nrwl/web']).toBeTruthy();
});

it('should not change anything if root babel.config.json is found', async () => {
tree.write('babel.config.json', '{"babelrcRoots": ["*"]}');
await update(tree);
const packageJson = readJson(tree, 'package.json');
expect(packageJson.devDependencies['@nrwl/web']).toBeFalsy();
});

it('should update w/ Array value for babel-jest transformer', async () => {
tree = createTreeWithEmptyWorkspace();

tree.write(
'libs/lib-three/jest.config.js',
String.raw`module.exports = {
transform: {
'^.+\\\\.[tj]sx?$': ['babel-jest', {someOptionsThatDontMatter: false}],
}
}`
);

addProjectConfiguration(tree, 'lib-three', {
root: 'libs/lib-three',
sourceRoot: 'libs/lib-three/src',
projectType: 'library',
targets: {
build: {
executor: '@nrwl/web:build',
},
test: {
executor: '@nrwl/jest:jest',
options: {
jestConfig: 'libs/lib-three/jest.config.js',
passWithNoTests: true,
},
},
},
});

await update(tree);
expect(tree.exists('babel.config.json')).toBeTruthy();
const packageJson = readJson(tree, 'package.json');
expect(packageJson.devDependencies['@nrwl/web']).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {
addDependenciesToPackageJson,
formatFiles,
joinPathFragments,
readProjectConfiguration,
Tree,
} from '@nrwl/devkit';
import { forEachExecutorOptions } from '@nrwl/workspace/src/utilities/executor-options-utils';
import { JestExecutorOptions } from '@nrwl/jest/src/executors/jest/schema';
import { jestConfigObject } from '../../utils/config/functions';
import { nxVersion } from '../../utils/versions';

function checkIfProjectNeedsUpdate(tree: Tree): boolean {
if (tree.exists('babel.config.json')) {
// the project is already running on babel and good to go
return false;
}

let shouldUpdate = false;
forEachExecutorOptions<JestExecutorOptions>(
tree,
'@nrwl/jest:jest',
(jestOptions, projectName) => {
const projectConfig = readProjectConfiguration(tree, projectName);
const jestConfigPath = joinPathFragments(
projectConfig.root,
'jest.config.js'
);

if (!tree.exists(jestConfigPath)) {
return;
}

const config = jestConfigObject(tree, jestConfigPath);

for (const transformer of Object.values(config.transform)) {
if (
(typeof transformer === 'string' && transformer === 'babel-jest') ||
(Array.isArray(transformer) && transformer[0] === 'babel-jest')
) {
shouldUpdate = true;
}
}
}
);

return shouldUpdate;
}

export default async function update(tree: Tree) {
const shouldUpdateConfigs = checkIfProjectNeedsUpdate(tree);

if (shouldUpdateConfigs) {
addDependenciesToPackageJson(tree, {}, { '@nrwl/web': nxVersion });

tree.write('babel.config.json', '{"babelrcRoots": ["*"]}');

await formatFiles(tree);
}
}

0 comments on commit baf44ad

Please sign in to comment.