-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
next.test.ts
486 lines (407 loc) · 12.5 KB
/
next.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import { stringUtils } from '@nrwl/workspace';
import {
checkFilesExist,
cleanupProject,
createFile,
expectJestTestsToPass,
isNotWindows,
killPorts,
newProject,
promisifiedTreeKill,
readFile,
readJson,
runCLI,
runCLIAsync,
runCommandUntil,
runCypressTests,
uniq,
updateFile,
updateProjectConfig,
} from '@nrwl/e2e/utils';
import * as http from 'http';
describe('Next.js Applications', () => {
let proj: string;
beforeAll(() => (proj = newProject()));
afterAll(() => cleanupProject());
it('should generate app + libs', async () => {
const appName = uniq('app');
const reactLib = uniq('reactlib');
const jsLib = uniq('tslib');
runCLI(`generate @nrwl/next:app ${appName} --no-interactive --style=css`);
runCLI(`generate @nrwl/react:lib ${reactLib} --no-interactive`);
runCLI(`generate @nrwl/js:lib ${jsLib} --no-interactive`);
// Create file in public that should be copied to dist
updateFile(`apps/${appName}/public/a/b.txt`, `Hello World!`);
// Additional assets that should be copied to dist
const sharedLib = uniq('sharedLib');
updateProjectConfig(appName, (json) => {
json.targets.build.options.assets = [
{
glob: '**/*',
input: `libs/${sharedLib}/src/assets`,
output: 'shared/ui',
},
];
return json;
});
updateFile(`libs/${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/@nrwl/next/test-styles.css',
'h1 { background-color: red; }'
);
updateFile(
`libs/${jsLib}/src/lib/${jsLib}.ts`,
`
export function testFn(): string {
return 'Hello Nx';
};
// testing whether async-await code in Node / Next.js api routes works as expected
export async function testAsyncFn() {
return await Promise.resolve('hell0');
}
`
);
const mainPath = `apps/${appName}/pages/index.tsx`;
const content = readFile(mainPath);
updateFile(
`apps/${appName}/pages/api/hello.ts`,
`
import { testAsyncFn } from '@${proj}/${jsLib}';
export default async function handler(_, res) {
const value = await testAsyncFn();
res.send(value);
}
`
);
updateFile(
mainPath,
`
import { testFn } from '@${proj}/${jsLib}';
/* eslint-disable */
import dynamic from 'next/dynamic';
const TestComponent = dynamic(
() => import('@${proj}/${reactLib}').then(d => d.${stringUtils.capitalize(
reactLib
)})
);
${content.replace(
`</h2>`,
`</h2>
<div>
{testFn()}
<TestComponent />
</div>
`
)}`
);
const e2eTestPath = `apps/${appName}-e2e/src/integration/app.spec.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,
});
// public and shared assets should both be copied to dist
checkFilesExist(
`dist/apps/${appName}/public/a/b.txt`,
`dist/apps/${appName}/public/shared/ui/hello.txt`
);
}, 300000);
it('should be able to serve with a proxy configuration', async () => {
const appName = uniq('app');
const jsLib = uniq('tslib');
const port = 4201;
runCLI(`generate @nrwl/next:app ${appName}`);
runCLI(`generate @nrwl/js:lib ${jsLib} --no-interactive`);
const proxyConf = {
'/external-api': {
target: `http://localhost:${port}`,
pathRewrite: {
'^/external-api/hello': '/api/hello',
},
},
};
updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf));
updateFile('.env.local', 'NX_CUSTOM_VAR=test value from a file');
updateFile(
`libs/${jsLib}/src/lib/${jsLib}.ts`,
`
export function testFn(): string {
return process.env.NX_CUSTOM_VAR;
};
`
);
updateFile(
`apps/${appName}/pages/index.tsx`,
`
import React from 'react';
import { testFn } from '@${proj}/${jsLib}';
export const Index = ({ greeting }: any) => {
return (
<p>{testFn()}</p>
);
};
export default Index;
`
);
updateFile(
`apps/${appName}/pages/api/hello.js`,
`
export default (_req, res) => {
res.status(200).send('Welcome');
};
`
);
// serve Next.js
const p = await runCommandUntil(
`run ${appName}:serve --port=${port}`,
(output) => {
return output.indexOf(`[ ready ] on http://localhost:${port}`) > -1;
}
);
const apiData = await getData(port, '/external-api/hello');
const pageData = await getData(port, '/');
expect(apiData).toContain(`Welcome`);
expect(pageData).toContain(`test value from a file`);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
expect(await killPorts(port)).toBeTruthy();
} catch (err) {
expect(err).toBeFalsy();
}
}, 300000);
it('should build with a next.config.js file in the dist folder', async () => {
const appName = uniq('app');
runCLI(`generate @nrwl/next:app ${appName} --no-interactive --style=css`);
updateFile(
`apps/${appName}/next.config.js`,
`
module.exports = {
webpack: (c) => {
console.log('NODE_ENV is', process.env.NODE_ENV);
return c;
}
}
`
);
// 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');
}, 300000);
it('should support --js flag', async () => {
const appName = uniq('app');
runCLI(`generate @nrwl/next:app ${appName} --no-interactive --js`);
checkFilesExist(`apps/${appName}/pages/index.js`);
await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: false,
checkExport: false,
});
// Consume a JS lib
const libName = uniq('lib');
runCLI(
`generate @nrwl/react:lib ${libName} --no-interactive --style=none --js`
);
const mainPath = `apps/${appName}/pages/index.js`;
updateFile(
mainPath,
`import '@${proj}/${libName}';\n` + readFile(mainPath)
);
// Update lib to use css modules
updateFile(
`libs/${libName}/src/lib/${libName}.js`,
`
import styles from './style.module.css';
export function Test() {
return <div className={styles.container}>Hello</div>;
}
`
);
updateFile(
`libs/${libName}/src/lib/style.module.css`,
`
.container {}
`
);
await checkApp(appName, {
checkUnitTest: true,
checkLint: true,
checkE2E: false,
checkExport: false,
});
}, 300000);
it('should support --no-swc flag', async () => {
const appName = uniq('app');
runCLI(`generate @nrwl/next:app ${appName} --no-interactive --no-swc`);
// Next.js enables SWC when custom .babelrc is not provided.
checkFilesExist(`apps/${appName}/.babelrc`);
await checkApp(appName, {
checkUnitTest: false,
checkLint: false,
checkE2E: false,
checkExport: true,
});
}, 300000);
it('should allow using a custom server implementation in TypeScript', async () => {
const appName = uniq('app');
const port = 4202;
// generate next.js app
runCLI(`generate @nrwl/next:app ${appName} --no-interactive`);
// create custom server
createFile(
'tools/custom-next-server.ts',
`
const express = require('express');
const path = require('path');
export default async function nextCustomServer(app, settings, proxyConfig) {
const handle = app.getRequestHandler();
await app.prepare();
const x: string = 'custom typescript server running';
console.log(x);
const server = express();
server.disable('x-powered-by');
server.use(
express.static(path.resolve(settings.dir, settings.conf.outdir, 'public'))
);
// Default catch-all handler to allow Next.js to handle all other routes
server.all('*', (req, res) => handle(req, res));
server.listen(settings.port, settings.hostname);
}
`
);
updateProjectConfig(appName, (config) => {
config.targets.serve.options.customServerPath =
'../../tools/custom-next-server.ts';
return config;
});
// serve Next.js
const p = await runCommandUntil(
`run ${appName}:serve --port=${port}`,
(output) => {
return output.indexOf(`[ ready ] on http://localhost:${port}`) > -1;
}
);
const data = await getData(port);
expect(data).toContain(`Welcome`);
try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
await killPorts(port);
} catch (err) {
expect(err).toBeFalsy();
}
}, 300000);
it('should support different --style options', async () => {
const lessApp = uniq('app');
runCLI(`generate @nrwl/next:app ${lessApp} --no-interactive --style=less`);
await checkApp(lessApp, {
checkUnitTest: false,
checkLint: false,
checkE2E: false,
checkExport: false,
});
const stylusApp = uniq('app');
runCLI(
`generate @nrwl/next:app ${stylusApp} --no-interactive --style=styl`
);
await checkApp(stylusApp, {
checkUnitTest: false,
checkLint: false,
checkE2E: false,
checkExport: false,
});
const scApp = uniq('app');
runCLI(
`generate @nrwl/next:app ${scApp} --no-interactive --style=styled-components`
);
await checkApp(scApp, {
checkUnitTest: true,
checkLint: false,
checkE2E: false,
checkExport: false,
});
const emotionApp = uniq('app');
runCLI(
`generate @nrwl/next:app ${emotionApp} --no-interactive --style=@emotion/styled`
);
await checkApp(emotionApp, {
checkUnitTest: true,
checkLint: false,
checkE2E: false,
checkExport: false,
});
}, 300000);
it('should run default jest tests', async () => {
await expectJestTestsToPass('@nrwl/next:app');
}, 100000);
});
function getData(port: number, path = ''): Promise<any> {
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', () => {
resolve(data);
});
});
});
}
async function checkApp(
appName: string,
opts: {
checkUnitTest: boolean;
checkLint: boolean;
checkE2E: boolean;
checkExport: boolean;
}
) {
const buildResult = runCLI(`build ${appName}`);
expect(buildResult).toContain(`Compiled successfully`);
checkFilesExist(`dist/apps/${appName}/.next/build-manifest.json`);
const packageJson = readJson(`dist/apps/${appName}/package.json`);
expect(packageJson.dependencies.react).toBeDefined();
expect(packageJson.dependencies['react-dom']).toBeDefined();
expect(packageJson.dependencies.next).toBeDefined();
if (opts.checkLint) {
const lintResults = runCLI(`lint ${appName}`);
expect(lintResults).toContain('All files pass linting.');
}
if (opts.checkUnitTest) {
const testResults = await runCLIAsync(`test ${appName}`);
expect(testResults.combinedOutput).toContain(
'Test Suites: 1 passed, 1 total'
);
}
if (opts.checkE2E && runCypressTests()) {
const e2eResults = runCLI(`e2e ${appName}-e2e --no-watch`);
expect(e2eResults).toContain('All specs passed!');
expect(await killPorts()).toBeTruthy();
}
if (opts.checkExport) {
runCLI(`export ${appName}`);
checkFilesExist(`dist/apps/${appName}/exported/index.html`);
}
}