import { checkFilesDoNotExist, checkFilesExist, cleanupProject, configureTargetOptions, createFile, killPorts, listFiles, newProject, readFile, reservePort, runCLI, runCLIAsync, uniq, updateFile, shouldRunPlaywrightTests, } from '@nx/e2e-utils'; import { readFileSync } from 'fs-extra'; import { join } from 'path'; describe('React Applications', () => { let proj: string; describe('Crystal Supported Tests', () => { beforeAll(() => { proj = newProject({ keepBackup: true, packages: [ '@nx/react', '@nx/webpack', '@nx/vite', '@nx/vitest', '@nx/jest', '@nx/cypress', '@nx/eslint', ], }); }); afterAll(() => cleanupProject()); it('should be able to use Vite to build and test apps', async () => { const appName = uniq('app'); const libName = uniq('lib'); const port = await reservePort(); runCLI( `generate @nx/react:app apps/${appName} --name=${appName} --bundler=vite --no-interactive --skipFormat --linter=eslint --unitTestRunner=vitest --port=${port}` ); runCLI( `generate @nx/react:lib libs/${libName} --bundler=none --no-interactive --unit-test-runner=vitest --skipFormat --linter=eslint` ); // Library generated with Vite checkFilesExist(`libs/${libName}/vite.config.mts`); const mainPath = `apps/${appName}/src/main.tsx`; updateFile( mainPath, ` import '@${proj}/${libName}'; ${readFile(mainPath)} ` ); runCLI(`build ${appName}`); checkFilesExist(`dist/apps/${appName}/index.html`); if (await shouldRunPlaywrightTests()) { const restoreServerOptions = configureTargetOptions( ['dev', 'preview'], { strictPort: true, } ); try { const e2eResults = runCLI(`e2e ${appName}-e2e`); expect(e2eResults).toContain( 'Successfully ran target e2e for project' ); expect(await killPorts(port)).toBeTruthy(); } finally { restoreServerOptions(); } } }, 250_000); it('should be able to generate a react app + lib', async () => { const appName = uniq('app'); const libName = uniq('lib'); const libWithNoComponents = uniq('lib'); const logoSvg = readFileSync(join(__dirname, 'logo.svg')).toString(); const blueSvg = ``; const redSvg = ``; runCLI( `generate @nx/react:app apps/${appName} --style=css --bundler=webpack --unit-test-runner=jest --no-interactive --skipFormat --linter=eslint` ); runCLI( `generate @nx/react:lib libs/${libName} --style=css --no-interactive --unit-test-runner=jest --skipFormat --linter=eslint` ); runCLI( `generate @nx/react:lib libs/${libWithNoComponents} --no-interactive --no-component --unit-test-runner=jest --skipFormat --linter=eslint` ); // Libs should not include package.json by default checkFilesDoNotExist(`libs/${libName}/package.json`); const mainPath = `apps/${appName}/src/main.tsx`; updateFile( mainPath, ` import '@${proj}/${libWithNoComponents}'; import '@${proj}/${libName}'; ${readFile(mainPath)} ` ); updateFile(`apps/${appName}/src/app/blue/img.svg`, blueSvg); // ensure that same filenames do not conflict updateFile(`apps/${appName}/src/app/red/img.svg`, redSvg); // ensure that same filenames do not conflict updateFile(`apps/${appName}/src/app/logo.svg`, logoSvg); updateFile( `apps/${appName}/src/app/app.tsx`, ` import { ReactComponent as Logo } from './logo.svg'; import blue from './blue/img.svg'; import red from './red/img.svg'; import logo from './logo.svg'; import NxWelcome from './nx-welcome'; export function App() { return ( <> ); } export default App; ` ); // Make sure global stylesheets are properly processed. const stylesPath = `apps/${appName}/src/styles.css`; updateFile( stylesPath, ` .foobar { background-image: url('/bg.png'); } ` ); const libTestResults = await runCLIAsync(`test ${libName}`); expect(libTestResults.combinedOutput).toContain( 'Test Suites: 1 passed, 1 total' ); await testGeneratedApp(appName, { checkSourceMap: true, checkStyles: true, checkLinter: true, // TODO(jack): check why Playwright tests are timing out in CI checkE2E: false, }); }, 500_000); it('should generate app with routing', async () => { const appName = uniq('app'); runCLI( `generate @nx/react:app apps/${appName} --routing --bundler=webpack --no-interactive --skipFormat --linter=eslint --unitTestRunner=jest` ); runCLI(`build ${appName}`); checkFilesExistWithHash(`dist/apps/${appName}`, [ `index.html`, `runtime.*.js`, `main.*.js`, ]); }, 250_000); it('should be able to add a redux slice', async () => { const appName = uniq('app'); const libName = uniq('lib'); runCLI( `g @nx/react:app apps/${appName} --bundler=webpack --no-interactive --skipFormat --unitTestRunner=jest --linter=eslint` ); runCLI( `g @nx/react:redux apps/${appName}/src/app/lemon/lemon --skipFormat` ); runCLI( `g @nx/react:lib libs/${libName} --unit-test-runner=jest --no-interactive --skipFormat` ); runCLI( `g @nx/react:redux libs/${libName}/src/lib/orange/orange --skipFormat` ); let lintResults = runCLI(`lint ${appName}`); expect(lintResults).toContain( `Successfully ran target lint for project ${appName}` ); const appTestResults = await runCLIAsync(`test ${appName}`); expect(appTestResults.combinedOutput).toContain( `Successfully ran target test for project ${appName}` ); lintResults = runCLI(`lint ${libName}`); expect(lintResults).toContain( `Successfully ran target lint for project ${libName}` ); const libTestResults = await runCLIAsync(`test ${libName}`); expect(libTestResults.combinedOutput).toContain( `Successfully ran target test for project ${libName}` ); }, 250_000); it('should support generating projects with the new name and root format', () => { const appName = uniq('app1'); const libName = uniq('@my-org/lib1'); runCLI( `generate @nx/react:app ${appName} --bundler=webpack --no-interactive --skipFormat --linter=eslint --unitTestRunner=jest` ); // check files are generated without the layout directory ("apps/") and // using the project name as the directory when no directory is provided checkFilesExist(`${appName}/src/main.tsx`); // check build works expect(runCLI(`build ${appName}`)).toContain( `Successfully ran target build for project ${appName}` ); // check tests pass const appTestResult = runCLI(`test ${appName}`); expect(appTestResult).toContain( `Successfully ran target test for project ${appName}` ); runCLI( `generate @nx/react:lib ${libName} --unit-test-runner=jest --buildable --no-interactive --skipFormat --linter=eslint` ); // check files are generated without the layout directory ("libs/") and // using the project name as the directory when no directory is provided checkFilesExist(`${libName}/src/index.ts`); // check build works expect(runCLI(`build ${libName}`)).toContain( `Successfully ran target build for project ${libName}` ); // check tests pass const libTestResult = runCLI(`test ${libName}`); expect(libTestResult).toContain( `Successfully ran target test for project ${libName}` ); }, 500_000); describe('--format', () => { it('should be formatted on freshly created apps', async () => { const appName = uniq('app'); runCLI( `generate @nx/react:app ${appName} --bundler=webpack --no-interactive --linter=eslint --unitTestRunner=jest` ); const stdout = runCLI(`format:check --projects=${appName}`, { silenceError: true, }); expect(stdout).toEqual(''); }); }); }); describe('Webpack apps', () => { beforeAll(() => { proj = newProject({ keepBackup: true, packages: [ '@nx/react', '@nx/webpack', '@nx/jest', '@nx/cypress', '@nx/eslint', ], }); }); afterAll(() => { cleanupProject(); }); it('should be able to use JS and JSX', async () => { const appName = uniq('app'); const libName = uniq('lib'); const plainJsLib = uniq('jslib'); runCLI( `generate @nx/react:app apps/${appName} --bundler=webpack --unit-test-runner=jest --no-interactive --js --skipFormat --linter=eslint` ); runCLI( `generate @nx/react:lib libs/${libName} --no-interactive --js --unit-test-runner=none --skipFormat --linter=eslint` ); // Make sure plain JS libs can be imported as well. // There was an issue previously: https://github.com/nrwl/nx/issues/10990 runCLI( `generate @nx/js:lib libs/${plainJsLib} --js --unit-test-runner=none --bundler=none --compiler=tsc --no-interactive --skipFormat --linter=eslint` ); const mainPath = `apps/${appName}/src/main.js`; updateFile( mainPath, `import '@${proj}/${libName}';\nimport '@${proj}/${plainJsLib}';\n${readFile( mainPath )}` ); await testGeneratedApp(appName, { checkStyles: true, checkLinter: false, checkE2E: false, }); }, 250_000); it.each` style ${'css'} ${'scss'} `('should support global and css modules', async ({ style }) => { const appName = uniq('app'); runCLI( `generate @nx/react:app apps/${appName} --style=${style} --bundler=webpack --no-interactive --skipFormat --linter=eslint --unitTestRunner=jest` ); // make sure stylePreprocessorOptions works updateFile(`apps/${appName}/webpack.config.js`, (content) => content.replace( 'new NxAppWebpackPlugin({', `new NxAppWebpackPlugin({ stylePreprocessorOptions: { includePaths: ['libs/shared/lib'] },` ) ); updateFile( `apps/${appName}/src/base.${style}`, `html { font-family: "Comic Sans MS"; }` ); updateFile( `apps/${appName}/src/styles.${style}`, `@import 'base.${style}';` ); updateFile( `apps/${appName}/src/app/app.module.${style}`, (s) => `@import '../base.${style}';\n${s}` ); updateFile( `libs/shared/lib/base.${style}`, `body { font-family: "Comic Sans MS"; }` ); runCLI(`build ${appName}`); const stylesFile = listFiles(`dist/apps/${appName}`).find((f) => /^styles\..*css$/.test(f) ); expect(readFile(`dist/apps/${appName}/${stylesFile}`)).toMatch( /Comic Sans MS/ ); }); describe('React Applications and Libs with PostCSS', () => { it('should support single path or auto-loading of PostCSS config files', async () => { const appName = uniq('app'); const libName = uniq('lib'); runCLI( `g @nx/react:app apps/${appName} --bundler=webpack --no-interactive --skipFormat` ); runCLI( `g @nx/react:lib libs/${libName} --no-interactive --unit-test-runner=none --skipFormat` ); const mainPath = `apps/${appName}/src/main.tsx`; updateFile( mainPath, `import '@${proj}/${libName}';\n${readFile(mainPath)}` ); createFile( `apps/${appName}/postcss.config.js`, ` console.log('HELLO FROM APP'); // need this output for e2e test module.exports = {}; ` ); createFile( `libs/${libName}/postcss.config.js`, ` console.log('HELLO FROM LIB'); // need this output for e2e test module.exports = {}; ` ); let buildResults = await runCLIAsync(`build ${appName}`); expect(buildResults.combinedOutput).toMatch(/HELLO FROM APP/); expect(buildResults.combinedOutput).toMatch(/HELLO FROM LIB/); // Only load app PostCSS config updateFile(`apps/${appName}/webpack.config.js`, (content) => content.replace( 'new NxAppWebpackPlugin({', `new NxAppWebpackPlugin({ postcssConfig: 'apps/${appName}/postcss.config.js',` ) ); buildResults = await runCLIAsync(`build ${appName}`); expect(buildResults.combinedOutput).toMatch(/HELLO FROM APP/); expect(buildResults.combinedOutput).not.toMatch(/HELLO FROM LIB/); }, 250_000); }); }); }); async function testGeneratedApp( appName, opts: { checkStyles: boolean; checkLinter: boolean; checkE2E: boolean; checkSourceMap?: boolean; } ) { if (opts.checkLinter) { const lintResults = runCLI(`lint ${appName}`); expect(lintResults).toContain( `Successfully ran target lint for project ${appName}` ); } runCLI(`build ${appName}`); const filesToCheck = [`index.html`, `runtime.*.js`, `main.*.js`]; if (opts.checkStyles) { filesToCheck.push(`styles.*.css`); expect( /styles.*.css/.test(readFile(`dist/apps/${appName}/index.html`)) ).toBeTruthy(); } checkFilesExistWithHash(`dist/apps/${appName}`, filesToCheck); const testResults = await runCLIAsync(`test ${appName}`); expect(testResults.combinedOutput).toContain( 'Test Suites: 1 passed, 1 total' ); if (opts.checkE2E && (await shouldRunPlaywrightTests())) { const e2eResults = runCLI(`e2e ${appName}-e2e`); expect(e2eResults).toContain('Successfully ran target e2e'); } } function checkFilesExistWithHash( outputDirToCheck: string, filesToCheck: string[] ) { const filesInOutputDir = listFiles(outputDirToCheck); // REGEX CHECK for (const fileToCheck of filesToCheck) { const regex = new RegExp(fileToCheck); let found = false; for (const fileInOutput of filesInOutputDir) { if (regex.test(fileInOutput)) { found = true; } } expect(found).toBeTruthy(); } }