Skip to content

Commit

Permalink
fix(vite): Failing to build when generated library uses jest (#13797)
Browse files Browse the repository at this point in the history
Co-authored-by: Nicholas Cunningham <ndcunningham>
  • Loading branch information
ndcunningham committed Dec 15, 2022
1 parent 5d64b1e commit 70e1aab
Show file tree
Hide file tree
Showing 17 changed files with 129 additions and 45 deletions.
21 changes: 19 additions & 2 deletions e2e/react/src/cypress-component-tests.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
runCLI,
uniq,
updateFile,
updateJson,
updateProjectConfig,
} from '../../utils';

Expand All @@ -16,13 +17,29 @@ describe('React Cypress Component Tests', () => {

beforeAll(() => {
projectName = newProject({ name: uniq('cy-react') });

runCLI(
`generate @nrwl/react:app ${appName} --bundler=webpack --no-interactive`
);

updateJson('nx.json', (json) => ({
...json,
generators: {
...json.generators,
'@nrwl/react': {
library: {
unitTestRunner: 'jest',
},
},
},
}));

runCLI(
`generate @nrwl/react:component fancy-cmp --project=${appName} --no-interactive`
);
runCLI(`generate @nrwl/react:lib ${usedInAppLibName} --no-interactive`);
runCLI(
`generate @nrwl/react:lib ${usedInAppLibName} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nrwl/react:component btn --project=${usedInAppLibName} --export --no-interactive`
);
Expand Down Expand Up @@ -83,7 +100,7 @@ export default App;`
);

runCLI(
`generate @nrwl/react:lib ${buildableLibName} --buildable --no-interactive`
`generate @nrwl/react:lib ${buildableLibName} --buildable --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nrwl/react:component input --project=${buildableLibName} --export --no-interactive`
Expand Down
4 changes: 3 additions & 1 deletion e2e/react/src/react-misc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ describe('React Applications: additional packages', () => {

runCLI(`g @nrwl/react:app ${appName} --bundler=webpack --no-interactive`);
runCLI(`g @nrwl/react:redux lemon --project=${appName}`);
runCLI(`g @nrwl/react:lib ${libName} --no-interactive`);
runCLI(
`g @nrwl/react:lib ${libName} --unit-test-runner=jest --no-interactive`
);
runCLI(`g @nrwl/react:redux orange --project=${libName}`);

const appTestResults = await runCLIAsync(`test ${appName}`);
Expand Down
31 changes: 22 additions & 9 deletions e2e/react/src/react-package.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
tmpProjPath,
uniq,
updateFile,
updateJson,
updateProjectConfig,
} from '@nrwl/e2e/utils';
import { names } from '@nrwl/devkit';
Expand Down Expand Up @@ -64,16 +65,26 @@ describe('Build React libraries and apps', () => {
};

runCLI(`generate @nrwl/react:app ${app} `);

updateJson('nx.json', (json) => ({
...json,
generators: {
...json.generators,
'@nrwl/react': {
library: {
unitTestRunner: 'none',
},
},
},
}));
// generate buildable libs
runCLI(
`generate @nrwl/react:library ${parentLib} --bundler=rollup --importPath=@${proj}/${parentLib} --no-interactive `
`generate @nrwl/react:library ${parentLib} --bundler=rollup --importPath=@${proj}/${parentLib} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nrwl/react:library ${childLib} --bundler=rollup --importPath=@${proj}/${childLib} --no-interactive `
`generate @nrwl/react:library ${childLib} --bundler=rollup --importPath=@${proj}/${childLib} --no-interactive --unitTestRunner=jest`
);
runCLI(
`generate @nrwl/react:library ${childLib2} --bundler=rollup --importPath=@${proj}/${childLib2} --no-interactive `
`generate @nrwl/react:library ${childLib2} --bundler=rollup --importPath=@${proj}/${childLib2} --no-interactive --unitTestRunner=jest`
);

createDep(parentLib, [childLib, childLib2]);
Expand Down Expand Up @@ -178,7 +189,7 @@ export async function h() { return 'c'; }
// Setup
const myLib = uniq('my-lib');
runCLI(
`generate @nrwl/react:library ${myLib} --bundler=rollup --publishable --importPath="@mproj/${myLib}" --no-interactive`
`generate @nrwl/react:library ${myLib} --bundler=rollup --publishable --importPath="@mproj/${myLib}" --no-interactive --unitTestRunner=jest`
);

/**
Expand Down Expand Up @@ -237,7 +248,7 @@ export async function h() { return 'c'; }
const libName = uniq('lib');

runCLI(
`generate @nrwl/react:lib ${libName} --bundler=rollup --importPath=@${proj}/${libName} --no-interactive`
`generate @nrwl/react:lib ${libName} --bundler=rollup --importPath=@${proj}/${libName} --no-interactive --unitTestRunner=jest`
);

const mainPath = `libs/${libName}/src/lib/${libName}.tsx`;
Expand Down Expand Up @@ -306,7 +317,7 @@ describe('Build React applications and libraries with Vite', () => {
checkFilesExist(`dist/apps/${viteApp}/index.html`);

runCLI(
`generate @nrwl/react:lib ${viteLib} --bundler=vite --inSourceTests --no-interactive`
`generate @nrwl/react:lib ${viteLib} --bundler=vite --inSourceTests --unitTestRunner=vitest --no-interactive`
);
expect(() => {
checkFilesExist(`libs/${viteLib}/src/lib/${viteLib}.spec.tsx`);
Expand Down Expand Up @@ -346,7 +357,7 @@ describe('Build React applications and libraries with Vite', () => {
const viteLib = uniq('vitelib');

runCLI(
`generate @nrwl/react:lib ${viteLib} --bundler=vite --no-interactive`
`generate @nrwl/react:lib ${viteLib} --bundler=vite --no-interactive --unit-test-runner=none`
);

const packageJson = readJson('package.json');
Expand All @@ -365,7 +376,9 @@ describe('Build React applications and libraries with Vite', () => {

// Convert non-buildable lib to buildable one
const nonBuildableLib = uniq('nonbuildablelib');
runCLI(`generate @nrwl/react:lib ${nonBuildableLib} --no-interactive`);
runCLI(
`generate @nrwl/react:lib ${nonBuildableLib} --no-interactive --unitTestRunner=none`
);
runCLI(
`generate @nrwl/vite:configuration ${nonBuildableLib} --uiFramework=react --no-interactive`
);
Expand Down
16 changes: 11 additions & 5 deletions e2e/react/src/react.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ describe('React Applications', () => {
runCLI(
`generate @nrwl/react:app ${appName} --style=css --bundler=webpack --no-interactive`
);
runCLI(`generate @nrwl/react:lib ${libName} --style=css --no-interactive`);
runCLI(
`generate @nrwl/react:lib ${libWithNoComponents} --no-interactive --no-component`
`generate @nrwl/react:lib ${libName} --style=css --no-interactive --unit-test-runner=jest`
);
runCLI(
`generate @nrwl/react:lib ${libWithNoComponents} --no-interactive --no-component --unit-test-runner=jest`
);

// Libs should not include package.json by default
Expand Down Expand Up @@ -80,7 +82,9 @@ describe('React Applications', () => {
runCLI(
`generate @nrwl/react:app ${appName} --bundler=webpack --no-interactive --js`
);
runCLI(`generate @nrwl/react:lib ${libName} --no-interactive --js`);
runCLI(
`generate @nrwl/react:lib ${libName} --no-interactive --js --unit-test-runner=none`
);

const mainPath = `apps/${appName}/src/main.js`;
updateFile(
Expand All @@ -103,7 +107,7 @@ describe('React Applications', () => {
`generate @nrwl/react:app ${appName} --bundler=vite --no-interactive`
);
runCLI(
`generate @nrwl/react:lib ${libName} --bundler=none --no-interactive`
`generate @nrwl/react:lib ${libName} --bundler=none --no-interactive --unit-test-runner=vitest`
);

// Library generated with Vite
Expand Down Expand Up @@ -230,7 +234,9 @@ describe('React Applications and Libs with PostCSS', () => {
const libName = uniq('lib');

runCLI(`g @nrwl/react:app ${appName} --bundler=webpack --no-interactive`);
runCLI(`g @nrwl/react:lib ${libName} --no-interactive`);
runCLI(
`g @nrwl/react:lib ${libName} --no-interactive --unit-test-runner=none`
);

const mainPath = `apps/${appName}/src/main.tsx`;
updateFile(
Expand Down
1 change: 1 addition & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@nrwl/workspace": "file:../workspace",
"@phenomnomnominal/tsquery": "4.1.1",
"chalk": "4.1.0",
"enquirer": "~2.3.6",
"minimatch": "3.0.5",
"semver": "7.3.4"
},
Expand Down
17 changes: 0 additions & 17 deletions packages/react/src/generators/application/application.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1004,21 +1004,4 @@ describe('app', () => {
}
);
});

describe('setting generator defaults', () => {
it('should set libraries to use vitest when app uses vite bundler', async () => {
await applicationGenerator(appTree, {
...schema,
name: 'my-app',
bundler: 'vite',
});

const workspace = readWorkspaceConfiguration(appTree);
expect(workspace.generators['@nrwl/react']).toMatchObject({
library: {
unitTestRunner: 'vitest',
},
});
});
});
});
2 changes: 1 addition & 1 deletion packages/react/src/generators/application/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export async function applicationGenerator(host: Tree, schema: Schema) {
uiFramework: 'react',
project: options.projectName,
newProject: true,
includeVitest: true,
includeVitest: options.unitTestRunner === 'vitest',
inSourceTests: options.inSourceTests,
});
tasks.push(viteTask);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ export function setDefaults(host: Tree, options: NormalizedSchema) {
linter: options.linter,
...prev.library,
};
// Future react libs should use same test runner as the app.
if (options.unitTestRunner === 'vitest') {
// Note: We don't set bundler: 'vite' for libraries because that means they are buildable.
libDefaults.unitTestRunner ??= 'vitest';
}

workspace.generators = {
...workspace.generators,
'@nrwl/react': {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { assertMinimumCypressVersion } from '@nrwl/cypress/src/utils/cypress-ver
import { Tree } from '@nrwl/devkit';
import { createTreeWithEmptyV1Workspace } from '@nrwl/devkit/testing';
import { Linter } from '@nrwl/linter';
import enquirer = require('enquirer');
import libraryGenerator from '../library/library';
import { componentTestGenerator } from './component-test';

Expand All @@ -13,6 +14,9 @@ describe(componentTestGenerator.name, () => {
> = assertMinimumCypressVersion as never;
beforeEach(() => {
tree = createTreeWithEmptyV1Workspace();
jest
.spyOn(enquirer, 'prompt')
.mockReturnValue(new Promise((res) => res({ runner: 'jest' })));
});
it('should create component test for tsx files', async () => {
mockedAssertMinimumCypressVersion.mockReturnValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { applicationGenerator } from '../application/application';
import { componentGenerator } from '../component/component';
import { libraryGenerator } from '../library/library';
import { cypressComponentConfigGenerator } from './cypress-component-configuration';
import enquirer = require('enquirer');

let projectGraph: ProjectGraph;
jest.mock('@nrwl/devkit', () => ({
Expand All @@ -29,6 +30,9 @@ describe('React:CypressComponentTestConfiguration', () => {
> = assertMinimumCypressVersion as never;
beforeEach(() => {
tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
jest
.spyOn(enquirer, 'prompt')
.mockReturnValue(new Promise((res) => res({ runner: 'jest' })));
});

it('should generate cypress config with vite', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ describe('normalizeOptions', () => {
name: 'test',
style: 'css',
linter: Linter.None,
unitTestRunner: 'jest',
});

expect(options).toMatchObject({
Expand Down Expand Up @@ -57,6 +58,7 @@ describe('normalizeOptions', () => {
style: 'css',
linter: Linter.None,
bundler: 'vite',
unitTestRunner: 'vitest',
});

expect(options).toMatchObject({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,6 @@ export function normalizeOptions(
normalized.bundler !== 'none' || options.buildable || options.publishable
);

normalized.unitTestRunner =
normalized.unitTestRunner ??
(normalized.bundler === 'vite' ? 'vitest' : 'jest');

normalized.inSourceTests === normalized.minimal || normalized.inSourceTests;

if (options.appProject) {
Expand Down
31 changes: 31 additions & 0 deletions packages/react/src/generators/library/lib/set-defaults.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {
readWorkspaceConfiguration,
Tree,
updateWorkspaceConfiguration,
} from '@nrwl/devkit';
import { NormalizedSchema } from '../schema';

export function setDefaults(host: Tree, options: NormalizedSchema) {
const workspace = readWorkspaceConfiguration(host);

workspace.generators = workspace.generators || {};
workspace.generators['@nrwl/react'] =
workspace.generators['@nrwl/react'] || {};

const prev = { ...workspace.generators['@nrwl/react'] };

const libDefaults = {
...prev.library,
unitTestRunner: prev.library?.unitTestRunner ?? options.unitTestRunner,
};

workspace.generators = {
...workspace.generators,
'@nrwl/react': {
...prev,
library: libDefaults,
},
};

updateWorkspaceConfiguration(host, workspace);
}
4 changes: 4 additions & 0 deletions packages/react/src/generators/library/library.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
createTreeWithEmptyWorkspace,
} from '@nrwl/devkit/testing';
import { Linter } from '@nrwl/linter';
import enquirer = require('enquirer');
import { nxVersion } from '../../utils/versions';
import applicationGenerator from '../application/application';
import libraryGenerator from './library';
Expand Down Expand Up @@ -370,6 +371,9 @@ describe('lib', () => {

describe('--unit-test-runner none', () => {
it('should not generate test configuration', async () => {
jest
.spyOn(enquirer, 'prompt')
.mockReturnValue(new Promise((res) => res({ runner: 'none' })));
await libraryGenerator(tree, {
...defaultSchema,
unitTestRunner: 'none',
Expand Down
19 changes: 18 additions & 1 deletion packages/react/src/generators/library/library.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,26 @@ import { createFiles } from './lib/create-files';
import { updateBaseTsConfig } from './lib/update-base-tsconfig';
import { extractTsConfigBase } from '../../utils/create-ts-config';
import { installCommonDependencies } from './lib/install-common-dependencies';
import { prompt } from 'enquirer';
import { setDefaults } from './lib/set-defaults';

export async function libraryGenerator(host: Tree, schema: Schema) {
const tasks: GeneratorCallback[] = [];

// Check if unit test runner was provided or if we have a default
if (!schema.unitTestRunner) {
schema.unitTestRunner = (
await prompt<{ runner: 'vitest' | 'jest' | 'none' }>([
{
message: 'What unit test runner should be used?',
type: 'select',
name: 'runner',
choices: ['vitest', 'jest', 'none'],
},
])
).runner;
}

const options = normalizeOptions(host, schema);
if (options.publishable === true && !schema.importPath) {
throw new Error(
Expand Down Expand Up @@ -80,7 +96,7 @@ export async function libraryGenerator(host: Tree, schema: Schema) {
newProject: true,
includeLib: true,
inSourceTests: options.inSourceTests,
includeVitest: true,
includeVitest: options.unitTestRunner === 'vitest',
});
tasks.push(viteTask);
} else if (options.buildable && options.bundler === 'rollup') {
Expand Down Expand Up @@ -159,6 +175,7 @@ export async function libraryGenerator(host: Tree, schema: Schema) {

const routeTask = updateAppRoutes(host, options);
tasks.push(routeTask);
setDefaults(host, options);

if (!options.skipFormat) {
await formatFiles(host);
Expand Down
Loading

0 comments on commit 70e1aab

Please sign in to comment.