import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { joinPathFragments } from '@nx/devkit'; import { checkFilesDoNotExist, checkFilesExist, cleanupProject, configureTargetOptions, createFile, detectPackageManager, getStrippedEnvironmentVariables, getPackageManagerCommand, newProject, reservePort, packageInstall, packageManagerLockFile, promisifiedTreeKill, readFile, runCLI, runCLIAsync, runCommand, runCommandUntil, tmpProjPath, uniq, updateFile, updateJson, } from '@nx/e2e-utils'; import { execSync } from 'child_process'; import * as http from 'http'; import { getLockFileName } from '@nx/js'; import { satisfies } from 'semver'; import { join } from 'path'; function getData(port, path = '/api'): Promise { return new Promise((resolve) => { http.get(`http://localhost:${port}${path}`, (res) => { expect(res.statusCode).toEqual(200); let data = ''; res.on('data', (chunk) => { data += chunk; }); res.once('end', () => { try { resolve(JSON.parse(data)); } catch (e) { resolve(data); } }); }); }); } describe('Node Applications', () => { let restoreServerPort: (() => void) | undefined; beforeAll(() => { newProject({ keepBackup: true, packages: [ '@nx/node', '@nx/express', '@nx/nest', '@nx/webpack', '@nx/jest', ], }); restoreServerPort = configureTargetOptions(['@nx/js:node'], { port: 0 }); }); afterAll(() => { restoreServerPort?.(); cleanupProject(); }); it('should be able to generate an empty application', async () => { const nodeapp = uniq('nodeapp'); runCLI( `generate @nx/node:app apps/${nodeapp} --linter=eslint --unitTestRunner=jest` ); expect(() => runCLI(`lint ${nodeapp}`)).not.toThrow(); expect(() => runCLI(`test ${nodeapp}`)).not.toThrow(); updateFile(`apps/${nodeapp}/src/main.ts`, `console.log('Hello World!');`); await runCLIAsync(`build ${nodeapp}`); checkFilesExist(`dist/apps/${nodeapp}/main.js`); const result = execSync(`node dist/apps/${nodeapp}/main.js`, { cwd: tmpProjPath(), }).toString(); expect(result).toContain('Hello World!'); }, 300000); // TODO(crystal, @ndcunningham): This does not work because NxWebpackPlugin({}) outputFilename does not work. xit('should be able to generate the correct outputFileName in options', async () => { const nodeapp = uniq('nodeapp'); runCLI( `generate @nx/node:app apps/${nodeapp} --linter=eslint --unitTestRunner=jest` ); updateJson(join('apps', nodeapp, 'project.json'), (config) => { config.targets.build.options.outputFileName = 'index.js'; return config; }); await runCLIAsync(`build ${nodeapp}`); checkFilesExist(`dist/apps/${nodeapp}/index.js`); }, 300000); it('should be able to generate an empty application with additional entries', async () => { const nodeapp = uniq('nodeapp'); runCLI( `generate @nx/node:app apps/${nodeapp} --linter=eslint --bundler=webpack --unitTestRunner=jest` ); const lintResults = runCLI(`lint ${nodeapp}`); expect(lintResults).toContain('Successfully ran target lint'); updateFile( `apps/${nodeapp}/webpack.config.js`, ` const { NxAppWebpackPlugin } = require('@nx/webpack/app-plugin'); const { join } = require('path'); module.exports = { output: { path: join(__dirname, '../../dist/apps/${nodeapp}'), }, plugins: [ new NxAppWebpackPlugin({ target: 'node', compiler: 'tsc', main: './src/main.ts', tsConfig: './tsconfig.app.json', assets: ['./src/assets'], additionalEntryPoints: [ { entryPath: 'apps/${nodeapp}/src/additional-main.ts', entryName: 'additional-main', } ], optimization: false, outputHashing: 'none', }), ], }; ` ); updateFile( `apps/${nodeapp}/src/additional-main.ts`, `console.log('Hello Additional World!');` ); updateFile( `apps/${nodeapp}/src/main.ts`, `console.log('Hello World!'); console.log('env: ' + process.env['NODE_ENV']); ` ); await runCLIAsync(`build ${nodeapp}`); checkFilesExist( `dist/apps/${nodeapp}/main.js`, `dist/apps/${nodeapp}/additional-main.js` ); const result = execSync( `NODE_ENV=development && node dist/apps/${nodeapp}/main.js`, { cwd: tmpProjPath(), } ).toString(); expect(result).toContain('Hello World!'); expect(result).toContain('env: development'); const additionalResult = execSync( `node dist/apps/${nodeapp}/additional-main.js`, { cwd: tmpProjPath(), } ).toString(); expect(additionalResult).toContain('Hello Additional World!'); }, 300_000); it('should be able to generate an empty application with variable in .env file', async () => { const port = await reservePort(); const nodeapp = uniq('nodeapp'); runCLI( `generate @nx/node:app apps/${nodeapp} --linter=eslint --bundler=webpack --framework=none --unitTestRunner=jest` ); updateFile('.env', `NX_FOOBAR="test foo bar"`); updateFile( `apps/${nodeapp}/src/main.ts`, `console.log('foobar: ' + process.env['NX_FOOBAR']);` ); await runCLIAsync(`build ${nodeapp}`); checkFilesExist(`dist/apps/${nodeapp}/main.js`); // check serving const p = await runCommandUntil( `serve ${nodeapp} --port=${port} --watch=false`, (output) => { process.stdout.write(output); return output.includes(`foobar: test foo bar`); }, { timeout: 120000, env: { NX_DAEMON: 'true', PORT: undefined, }, } ); await promisifiedTreeKill(p.pid, 'SIGKILL'); }, 60000); it("should exclude 'test' target from e2e project that uses jest", async () => { const appName = uniq('nodeapp'); runCLI( `generate @nx/node:app ${appName} --no-interactive --unitTestRunner=jest --linter=eslint --e2eTestRunner=jest` ); const nxJson = JSON.parse(readFile('nx.json')); expect(nxJson.plugins).toBeDefined(); const jestPlugin = nxJson.plugins.find( (p) => p.plugin === '@nx/jest/plugin' ); expect(jestPlugin).toBeDefined(); expect(jestPlugin.exclude).toContain(`${appName}-e2e/**/*`); }); it('should be able to generate an express application', async () => { const nodeapp = uniq('nodeapp'); const port = await reservePort(); runCLI( `generate @nx/express:app apps/${nodeapp} --port=${port} --linter=eslint --unitTestRunner=jest` ); const lintResults = runCLI(`lint ${nodeapp}`); expect(lintResults).toContain('Successfully ran target lint'); updateFile( `apps/${nodeapp}/src/app/test.spec.ts`, ` describe('test', () => { it('should work', () => { expect(true).toEqual(true); }) }) ` ); const jestResult = runCLI(`test ${nodeapp}`); expect(jestResult).toContain('Successfully ran target test'); // checking serve updateFile(`apps/${nodeapp}/src/assets/file.txt`, `Test`); const p = await runCommandUntil( `serve ${nodeapp}`, (output) => output.includes(`Listening at http://localhost:${port}`), { timeout: 120000, env: { NX_DAEMON: 'true', PORT: `${port}`, }, } ); try { let result = await getData(port); expect(result.message).toMatch(`Welcome to ${nodeapp}!`); result = await getData(port, '/assets/file.txt'); expect(result).toMatch(`Test`); } finally { await promisifiedTreeKill(p.pid, 'SIGKILL'); } }, 120_000); it('should be able to generate a nest application', async () => { const nestapp = uniq('nestapp'); const httpPort = await reservePort(); const e2eHttpPort = await reservePort(); const inspectPort = await reservePort(); runCLI( `generate @nx/nest:app apps/${nestapp} --linter=eslint --unitTestRunner=vitest` ); const lintResults = runCLI(`lint ${nestapp}`); expect(lintResults).toContain('Successfully ran target lint'); updateFile(`apps/${nestapp}/src/assets/file.txt`, ``); const testResult = await runCLIAsync(`test ${nestapp}`); expect(testResult.combinedOutput).toMatch(/Test Files\s+2 passed/); const buildResult = runCLI(`build ${nestapp}`); checkFilesExist( `dist/apps/${nestapp}/main.js`, `dist/apps/${nestapp}/assets/file.txt` ); expect(buildResult).toContain( `Successfully ran target build for project ${nestapp}` ); // checking serve const p = await runCommandUntil( `serve ${nestapp} --port=${inspectPort}`, (output) => { process.stdout.write(output); return output.includes(`listening on ws://localhost:${inspectPort}`); }, { timeout: 120000, env: { NX_DAEMON: 'true', PORT: `${httpPort}`, }, } ); await promisifiedTreeKill(p.pid, 'SIGKILL'); const e2eRsult = await runCLIAsync(`e2e ${nestapp}-e2e`, { env: { ...getStrippedEnvironmentVariables(), PORT: `${e2eHttpPort}` }, }); expect(e2eRsult.combinedOutput).toContain('Test Suites: 1 passed, 1 total'); }, 240000); it('should generate a nest application with docker', async () => { const nestapp = 'node-nest-docker-test'; runCLI( `generate @nx/node:app ${nestapp} --bundler=webpack --framework=nest --docker --unitTestRunner=vitest` ); checkFilesExist(`${nestapp}/Dockerfile`); }); // TODO(crystal, @ndcunningham): how do we handle this now? // Revisit when NxWebpackPlugin({}) outputFilename is working. xit('should be able to run ESM applications', async () => { const esmapp = uniq('esmapp'); runCLI( `generate @nx/node:app ${esmapp} --linter=eslint --framework=none --bundler=webpack --unitTestRunner=jest` ); updateJson(`apps/${esmapp}/tsconfig.app.json`, (config) => { config.module = 'esnext'; config.target = 'es2020'; return config; }); updateJson(join('apps', esmapp, 'project.json'), (config) => { config.targets.build.options.outputFileName = 'main.mjs'; config.targets.build.options.assets = []; return config; }); updateFile( `apps/${esmapp}/webpack.config.js`, ` const { composePlugins, withNx } = require('@nx/webpack'); module.exports = composePlugins(withNx(), (config) => { config.experiments = { ...config.experiments, outputModule: true, topLevelAwait: true, }; config.output = { path: config.output.path, chunkFormat: 'module', library: { type: 'module' } } return config; }); ` ); await runCLIAsync(`build ${esmapp}`); const p = await runCommandUntil( `serve ${esmapp}`, (output) => { return output.includes('Hello World'); }, { timeout: 120000, env: { NX_DAEMON: 'true', }, } ); await promisifiedTreeKill(p.pid, 'SIGKILL'); }, 300000); }); describe('Build Node apps', () => { let scope: string; beforeAll(() => { scope = newProject({ keepBackup: true, packages: [ '@nx/node', '@nx/express', '@nx/nest', '@nx/webpack', '@nx/jest', ], }); }); afterAll(() => { cleanupProject(); }); // TODO(crystal, @ndcunningham): What is the alternative here? xit('should generate a package.json with the `--generatePackageJson` flag', async () => { const packageManager = detectPackageManager(tmpProjPath()); const nestapp = uniq('nestapp'); runCLI( `generate @nx/nest:app apps/${nestapp} --linter=eslint --unitTestRunner=vitest` ); await runCLIAsync(`build ${nestapp} --generatePackageJson`); checkFilesExist(`dist/apps/${nestapp}/package.json`); checkFilesExist( `dist/apps/${nestapp}/${getLockFileName( detectPackageManager(tmpProjPath()) )}` ); const rootPackageJson = JSON.parse(readFile(`package.json`)); const packageJson = JSON.parse( readFile(`dist/apps/${nestapp}/package.json`) ); expect(packageJson).toEqual( expect.objectContaining({ main: 'main.js', name: expect.any(String), version: '0.0.1', }) ); expect( satisfies( packageJson.dependencies['@nestjs/common'], rootPackageJson.dependencies['@nestjs/common'] ) ).toBeTruthy(); expect( satisfies( packageJson.dependencies['@nestjs/core'], rootPackageJson.dependencies['@nestjs/core'] ) ).toBeTruthy(); expect( satisfies( packageJson.dependencies['reflect-metadata'], rootPackageJson.dependencies['reflect-metadata'] ) ).toBeTruthy(); expect( satisfies( packageJson.dependencies['rxjs'], rootPackageJson.dependencies['rxjs'] ) ).toBeTruthy(); expect( satisfies( packageJson.dependencies['tslib'], rootPackageJson.dependencies['tslib'] ) ).toBeTruthy(); checkFilesExist( `dist/apps/${nestapp}/${packageManagerLockFile[packageManager]}` ); runCommand(`${getPackageManagerCommand().ciInstall}`, { cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nestapp), }); const nodeapp = uniq('nodeapp'); runCLI( `generate @nx/node:app ${nodeapp} --bundler=webpack --unitTestRunner=jest --linter=eslint` ); const jslib = uniq('jslib'); runCLI(`generate @nx/js:lib ${jslib} --bundler=tsc`); updateFile( `apps/${nodeapp}/src/main.ts`, ` import { ${jslib} } from '@${scope}/${jslib}'; console.log('Hello World!'); ${jslib}(); ` ); const { combinedOutput: nodeCombinedOutput } = await runCLIAsync( `build ${nodeapp} --generate-package-json` ); expect(nodeCombinedOutput).not.toMatch(/Graph is not consistent/); checkFilesExist(`dist/apps/${nodeapp}/package.json`); checkFilesExist( `dist/apps/${nodeapp}/${packageManagerLockFile[packageManager]}` ); const nodeAppPackageJson = JSON.parse( readFile(`dist/apps/${nodeapp}/package.json`) ); expect(nodeAppPackageJson['dependencies']['tslib']).toBeTruthy(); runCommand(`${getPackageManagerCommand().ciInstall}`, { cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nestapp), }); runCommand(`${getPackageManagerCommand().ciInstall}`, { cwd: joinPathFragments(tmpProjPath(), 'dist/apps', nodeapp), }); }, 1_000_000); it('should remove previous output before building with the --deleteOutputPath option set', async () => { const appName = uniq('app'); runCLI( `generate @nx/node:app apps/${appName} --no-interactive --linter=eslint --unitTestRunner=jest` ); // deleteOutputPath should default to true createFile(`dist/apps/${appName}/_should_remove.txt`); createFile(`dist/apps/_should_not_remove.txt`); checkFilesExist( `dist/apps/${appName}/_should_remove.txt`, `dist/apps/_should_not_remove.txt` ); runCLI(`build ${appName} --outputHashing none`); // no explicit deleteOutputPath option set checkFilesDoNotExist(`dist/apps/${appName}/_should_remove.txt`); checkFilesExist(`dist/apps/_should_not_remove.txt`); }, 120000); it('should support generating projects with the new name and root format', async () => { const appName = uniq('app1'); const libName = uniq('@my-org/lib1'); runCLI( `generate @nx/node:app ${appName} --no-interactive --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.ts`); // check build works expect(runCLI(`build ${appName}`)).toContain( `Successfully ran target build for project ${appName}` ); // check tests pass const appTestResult = runCLI(`test ${appName} --passWithNoTests`); expect(appTestResult).toContain( `Successfully ran target test for project ${appName}` ); runCLI( `generate @nx/node:lib ${libName} --buildable --no-interactive --linter=eslint --unitTestRunner=jest` ); // 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); // TODO(crystal, @ndcunningnam): Investigate why these tests are failing xdescribe('NestJS', () => { // TODO(crystal, @ndcunningham): What is the alternative here? xit('should have plugin output if specified in `tsPlugins`', async () => { const nestapp = uniq('nestapp'); runCLI( `generate @nx/nest:app ${nestapp} --linter=eslint --unitTestRunner=vitest` ); packageInstall('@nestjs/swagger', undefined, '^12.0.0'); updateJson(join('apps', nestapp, 'project.json'), (config) => { config.targets.build.options.tsPlugins = ['@nestjs/swagger/plugin']; return config; }); updateFile( `apps/${nestapp}/src/app/foo.dto.ts`, ` export class FooDto { foo: string; bar: number; }` ); updateFile( `apps/${nestapp}/src/app/app.controller.ts`, ` import { Controller, Get } from '@nestjs/common'; import { FooDto } from './foo.dto'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Get() getData() { return this.appService.getData(); } @Get('foo') getFoo(): Promise { return Promise.resolve({ foo: 'foo', bar: 123 }) } }` ); await runCLIAsync(`build ${nestapp}`); const mainJs = readFile(`dist/apps/${nestapp}/main.js`); expect(mainJs).toContain('FooDto'); expect(mainJs).toContain('_OPENAPI_METADATA_FACTORY'); }, 300000); }); describe('nest libraries', function () { it('should be able to generate a nest library', async () => { const nestlib = uniq('nestlib'); runCLI( `generate @nx/nest:lib libs/${nestlib} --linter=eslint --unitTestRunner=vitest` ); const lintResults = runCLI(`lint ${nestlib}`); expect(lintResults).toContain('Successfully ran target lint'); const testResults = runCLI(`test ${nestlib} --passWithNoTests`); expect(testResults).toContain( `Successfully ran target test for project ${nestlib}` ); }, 60000); it('should be able to generate a nest library w/ service', async () => { const nestlib = uniq('nestlib'); runCLI( `generate @nx/nest:lib ${nestlib} --service --linter=eslint --unitTestRunner=vitest` ); const lintResults = runCLI(`lint ${nestlib}`); expect(lintResults).toContain('Successfully ran target lint'); const testResult = await runCLIAsync(`test ${nestlib}`); expect(testResult.combinedOutput).toMatch(/Test Files\s+1 passed/); }, 200000); it('should be able to generate a nest library w/ controller', async () => { const nestlib = uniq('nestlib'); runCLI( `generate @nx/nest:lib ${nestlib} --controller --linter=eslint --unitTestRunner=vitest` ); const lintResults = runCLI(`lint ${nestlib}`); expect(lintResults).toContain('Successfully ran target lint'); const testResult = await runCLIAsync(`test ${nestlib}`); expect(testResult.combinedOutput).toMatch(/Test Files\s+1 passed/); }, 200000); it('should be able to generate a nest library w/ controller and service', async () => { const nestlib = uniq('nestlib'); runCLI( `generate @nx/nest:lib ${nestlib} --controller --service --linter=eslint --unitTestRunner=vitest` ); const lintResults = runCLI(`lint ${nestlib}`); expect(lintResults).toContain('Successfully ran target lint'); const testResult = await runCLIAsync(`test ${nestlib}`); expect(testResult.combinedOutput).toMatch(/Test Files\s+2 passed/); }, 200000); it('should have plugin output if specified in `transformers`', async () => { const nestlib = uniq('nestlib'); runCLI( `generate @nx/nest:lib libs/${nestlib} --buildable --linter=eslint --unitTestRunner=vitest` ); packageInstall('@nestjs/swagger', undefined, '^12.0.0'); updateJson(join('libs', nestlib, 'project.json'), (config) => { config.targets.build.options.transformers = [ { name: '@nestjs/swagger/plugin', options: { dtoFileNameSuffix: ['.model.ts'], }, }, ]; return config; }); updateFile( `libs/${nestlib}/src/lib/foo.model.ts`, ` export class FooModel { foo?: string; bar?: number; }` ); await runCLIAsync(`build ${nestlib}`); const fooModelJs = readFile(`dist/libs/${nestlib}/src/lib/foo.model.js`); expect(stripIndents`${fooModelJs}`).toContain( stripIndents` "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FooModel = void 0; const openapi = require("@nestjs/swagger"); class FooModel { static _OPENAPI_METADATA_FACTORY() { return { foo: { required: false, type: () => String }, bar: { required: false, type: () => Number } }; } } exports.FooModel = FooModel; //# sourceMappingURL=foo.model.js.map ` ); }, 300000); }); });