Skip to content

Commit

Permalink
fix(nextjs): improve e2e test by reusing the project
Browse files Browse the repository at this point in the history
  • Loading branch information
ndcunningham committed Aug 25, 2023
1 parent ac0a871 commit f0b9931
Show file tree
Hide file tree
Showing 20 changed files with 476 additions and 298 deletions.
3 changes: 2 additions & 1 deletion CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ pnpm-lock.yaml @nrwl/nx-core-reviewers
/e2e/react-core/** @nrwl/nx-react-reviewers
/e2e/react-extensions/** @nrwl/nx-react-reviewers
/packages/next/** @nrwl/nx-react-reviewers
/e2e/next/** @nrwl/nx-react-reviewers
/e2e/next-core/** @nrwl/nx-react-reviewers
/e2e/next-extensions/** @nrwl/nx-react-reviewers
/packages/react/plugins/component-testing/** @nrwl/nx-react-reviewers @nrwl/nx-testing-tools-reviewers
/packages/react/src/generators/cypress-component-configuration/** @nrwl/nx-react-reviewers @nrwl/nx-testing-tools-reviewers
/packages/react/src/generators/component-test/** @nrwl/nx-react-reviewers @nrwl/nx-testing-tools-reviewers
Expand Down
2 changes: 1 addition & 1 deletion e2e/next/jest.config.ts → e2e/next-core/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export default {
globals: {},
globalSetup: '../utils/global-setup.ts',
globalTeardown: '../utils/global-teardown.ts',
displayName: 'e2e-next',
displayName: 'e2e-next-core',
preset: '../../jest.preset.js',
};
4 changes: 2 additions & 2 deletions e2e/next/project.json → e2e/next-core/project.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "e2e-next",
"name": "e2e-next-core",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "e2e/next",
"sourceRoot": "e2e/next-core/src",
"projectType": "application",
"targets": {
"e2e": {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,9 @@ import { checkApp } from './utils';
describe('Next.js App Router', () => {
let proj: string;

beforeEach(() => {
proj = newProject();
});
beforeAll(() => (proj = newProject()));

afterEach(() => {
cleanupProject();
});
afterAll(() => cleanupProject());

it('should be able to generate and build app with default App Router', async () => {
const appName = uniq('app');
Expand Down
43 changes: 43 additions & 0 deletions e2e/next-core/src/next-lock-file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { detectPackageManager, joinPathFragments } from '@nx/devkit';
import {
checkFilesExist,
cleanupProject,
getPackageManagerCommand,
newProject,
packageManagerLockFile,
runCLI,
runCommand,
tmpProjPath,
uniq,
} from '@nx/e2e/utils';

describe('Next.js Lock File', () => {
let proj: string;
let originalEnv: string;
let packageManager;

beforeEach(() => {
proj = newProject();
packageManager = detectPackageManager(tmpProjPath());
originalEnv = process.env.NODE_ENV;
});

afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});

it('should build and install pruned lock file', () => {
const appName = uniq('app');
runCLI(`generate @nx/next:app ${appName} --no-interactive --style=css`);

const result = runCLI(`build ${appName} --generateLockfile=true`);
expect(result).not.toMatch(/Graph is not consistent/);
checkFilesExist(
`dist/apps/${appName}/${packageManagerLockFile[packageManager]}`
);
runCommand(`${getPackageManagerCommand().ciInstall}`, {
cwd: joinPathFragments(tmpProjPath(), 'dist/apps', appName),
});
}, 1_000_000);
});
205 changes: 205 additions & 0 deletions e2e/next-core/src/next-structure.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { removeSync, mkdirSync } from 'fs-extra';
import { capitalize } from '@nx/devkit/src/utils/string-utils';
import { checkApp } from './utils';
import {
checkFilesExist,
cleanupProject,
isNotWindows,
killPort,
newProject,
readFile,
runCLI,
runCommandUntil,
tmpProjPath,
uniq,
updateFile,
updateProjectConfig,
} from '@nx/e2e/utils';

describe('Next.js Apps Libs', () => {
let proj: string;
let originalEnv: string;

beforeEach(() => {
proj = newProject();
originalEnv = process.env.NODE_ENV;
});

afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});

it('should generate app + libs', async () => {
// Remove apps/libs folder and use packages.
// Allows us to test other integrated monorepo setup that had a regression.
// See: https://github.com/nrwl/nx/issues/16658
removeSync(`${tmpProjPath()}/libs`);
removeSync(`${tmpProjPath()}/apps`);
mkdirSync(`${tmpProjPath()}/packages`);

const appName = uniq('app');
const nextLib = uniq('nextlib');
const jsLib = uniq('tslib');
const buildableLib = uniq('buildablelib');

runCLI(
`generate @nx/next:app ${appName} --no-interactive --style=css --appDir=false`
);
runCLI(`generate @nx/next:lib ${nextLib} --no-interactive`);
runCLI(`generate @nx/js:lib ${jsLib} --no-interactive`);
runCLI(
`generate @nx/js:lib ${buildableLib} --no-interactive --bundler=vite`
);

// Create file in public that should be copied to dist
updateFile(`packages/${appName}/public/a/b.txt`, `Hello World!`);

// Additional assets that should be copied to dist
const sharedLib = uniq('sharedLib');
await updateProjectConfig(appName, (json) => {
json.targets.build.options.assets = [
{
glob: '**/*',
input: `packages/${sharedLib}/src/assets`,
output: 'shared/ui',
},
];
return json;
});
updateFile(`packages/${sharedLib}/src/assets/hello.txt`, 'Hello World!');

// create a css file in node_modules so that it can be imported in a lib
// to test that it works as expected
updateFile(
'node_modules/@nx/next/test-styles.css',
'h1 { background-color: red; }'
);

updateFile(
`packages/${jsLib}/src/lib/${jsLib}.ts`,
`
export function jsLib(): string {
return 'Hello Nx';
};
// testing whether async-await code in Node / Next.js api routes works as expected
export async function jsLibAsync() {
return await Promise.resolve('hell0');
}
`
);

updateFile(
`packages/${buildableLib}/src/lib/${buildableLib}.ts`,
`
export function buildableLib(): string {
return 'Hello Buildable';
};
`
);

const mainPath = `packages/${appName}/pages/index.tsx`;
const content = readFile(mainPath);

updateFile(
`packages/${appName}/pages/api/hello.ts`,
`
import { jsLibAsync } from '@${proj}/${jsLib}';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default async function handler(_: any, res: any) {
const value = await jsLibAsync();
res.send(value);
}
`
);

updateFile(
mainPath,
`
import { jsLib } from '@${proj}/${jsLib}';
import { buildableLib } from '@${proj}/${buildableLib}';
/* eslint-disable */
import dynamic from 'next/dynamic';
const TestComponent = dynamic(
() => import('@${proj}/${nextLib}').then(d => d.${capitalize(
nextLib
)})
);
${content.replace(
`</h2>`,
`</h2>
<div>
{jsLib()}
{buildableLib()}
<TestComponent />
</div>
`
)}`
);

const e2eTestPath = `packages/${appName}-e2e/src/e2e/app.cy.ts`;
const e2eContent = readFile(e2eTestPath);
updateFile(
e2eTestPath,
`
${
e2eContent +
`
it('should successfully call async API route', () => {
cy.request('/api/hello').its('body').should('include', 'hell0');
});
`
}
`
);

await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: isNotWindows(),
checkExport: false,
appsDir: 'packages',
});

// public and shared assets should both be copied to dist
checkFilesExist(
`dist/packages/${appName}/public/a/b.txt`,
`dist/packages/${appName}/public/shared/ui/hello.txt`
);

// Check that compiled next config does not contain bad imports
const nextConfigPath = `dist/packages/${appName}/next.config.js`;
expect(nextConfigPath).not.toContain(`require("../`); // missing relative paths
expect(nextConfigPath).not.toContain(`require("nx/`); // dev-only packages
expect(nextConfigPath).not.toContain(`require("@nx/`); // dev-only packages

// Check that `nx serve <app> --prod` works with previous production build (e.g. `nx build <app>`).
const prodServePort = 4000;
const prodServeProcess = await runCommandUntil(
`run ${appName}:serve --prod --port=${prodServePort}`,
(output) => {
return output.includes(`localhost:${prodServePort}`);
}
);

// Check that the output is self-contained (i.e. can run with its own package.json + node_modules)
const selfContainedPort = 3000;
runCLI(
`generate @nx/workspace:run-commands serve-prod --project ${appName} --cwd=dist/packages/${appName} --command="npx next start --port=${selfContainedPort}"`
);
const selfContainedProcess = await runCommandUntil(
`run ${appName}:serve-prod`,
(output) => {
return output.includes(`localhost:${selfContainedPort}`);
}
);

prodServeProcess.kill();
selfContainedProcess.kill();
await killPort(prodServePort);
await killPort(selfContainedPort);
}, 600_000);
});
98 changes: 98 additions & 0 deletions e2e/next-core/src/next-webpack.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
checkFilesExist,
cleanupProject,
newProject,
rmDist,
runCLI,
uniq,
updateFile,
updateProjectConfig,
} from '@nx/e2e/utils';

describe('Next.js Webpack', () => {
let proj: string;
let originalEnv: string;

beforeEach(() => {
proj = newProject();
originalEnv = process.env.NODE_ENV;
});

afterEach(() => {
process.env.NODE_ENV = originalEnv;
cleanupProject();
});

it('should support custom webpack and run-commands using withNx', async () => {
const appName = uniq('app');

runCLI(
`generate @nx/next:app ${appName} --no-interactive --style=css --appDir=false`
);

updateFile(
`apps/${appName}/next.config.js`,
`
const { withNx } = require('@nx/next');
const nextConfig = {
nx: {
svgr: false,
},
webpack: (config, context) => {
// Make sure SVGR plugin is disabled if nx.svgr === false (see above)
const found = config.module.rules.find(r => {
if (!r.test || !r.test.test('test.svg')) return false;
if (!r.oneOf || !r.oneOf.use) return false;
return r.oneOf.use.some(rr => /svgr/.test(rr.loader));
});
if (found) throw new Error('Found SVGR plugin');
console.log('NODE_ENV is', process.env.NODE_ENV);
return config;
}
};
module.exports = withNx(nextConfig);
`
);
// deleting `NODE_ENV` value, so that it's `undefined`, and not `"test"`
// by the time it reaches the build executor.
// this simulates existing behaviour of running a next.js build executor via Nx
delete process.env.NODE_ENV;
const result = runCLI(`build ${appName}`);

checkFilesExist(`dist/apps/${appName}/next.config.js`);
expect(result).toContain('NODE_ENV is production');

updateFile(
`apps/${appName}/next.config.js`,
`
const { withNx } = require('@nx/next');
// Not including "nx" entry should still work.
const nextConfig = {};
module.exports = withNx(nextConfig);
`
);
rmDist();
runCLI(`build ${appName}`);
checkFilesExist(`dist/apps/${appName}/next.config.js`);

// Make sure withNx works with run-commands.
await updateProjectConfig(appName, (json) => {
json.targets.build = {
command: 'npx next build',
outputs: [`apps/${appName}/.next`],
options: {
cwd: `apps/${appName}`,
},
};
return json;
});
expect(() => {
runCLI(`build ${appName}`);
}).not.toThrow();
checkFilesExist(`apps/${appName}/.next/build-manifest.json`);
}, 300_000);
});
Loading

0 comments on commit f0b9931

Please sign in to comment.