-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
next-test-utils.js
683 lines (590 loc) · 17.1 KB
/
next-test-utils.js
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import spawn from 'cross-spawn'
import express from 'express'
import {
existsSync,
readFileSync,
unlinkSync,
writeFileSync,
createReadStream,
} from 'fs'
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import http from 'http'
import server from 'next/dist/server/next'
import _pkg from 'next/package.json'
import fetch from 'node-fetch'
import path from 'path'
import qs from 'querystring'
import treeKill from 'tree-kill'
export const nextServer = server
export const pkg = _pkg
// polyfill Object.fromEntries for the test/integration/relay-analytics tests
// on node 10, this can be removed after we no longer support node 10
if (!Object.fromEntries) {
Object.fromEntries = require('core-js/features/object/from-entries')
}
export function initNextServerScript(
scriptPath,
successRegexp,
env,
failRegexp,
opts
) {
return new Promise((resolve, reject) => {
const instance = spawn('node', ['--no-deprecation', scriptPath], {
env,
cwd: opts && opts.cwd,
})
function handleStdout(data) {
const message = data.toString()
if (successRegexp.test(message)) {
resolve(instance)
}
process.stdout.write(message)
if (opts && opts.onStdout) {
opts.onStdout(message.toString())
}
}
function handleStderr(data) {
const message = data.toString()
if (failRegexp && failRegexp.test(message)) {
instance.kill()
return reject(new Error('received failRegexp'))
}
process.stderr.write(message)
if (opts && opts.onStderr) {
opts.onStderr(message.toString())
}
}
instance.stdout.on('data', handleStdout)
instance.stderr.on('data', handleStderr)
instance.on('close', () => {
instance.stdout.removeListener('data', handleStdout)
instance.stderr.removeListener('data', handleStderr)
})
instance.on('error', (err) => {
reject(err)
})
})
}
export function getFullUrl(appPortOrUrl, url, hostname) {
let fullUrl =
typeof appPortOrUrl === 'string' && appPortOrUrl.startsWith('http')
? appPortOrUrl
: `http://${hostname ? hostname : 'localhost'}:${appPortOrUrl}${url}`
if (typeof appPortOrUrl === 'string' && url) {
const parsedUrl = new URL(fullUrl)
const parsedPathQuery = new URL(url, fullUrl)
parsedUrl.search = parsedPathQuery.search
parsedUrl.pathname = parsedPathQuery.pathname
fullUrl = parsedUrl.toString()
}
return fullUrl
}
export function renderViaAPI(app, pathname, query) {
const url = `${pathname}${query ? `?${qs.stringify(query)}` : ''}`
return app.renderToHTML({ url }, {}, pathname, query)
}
export function renderViaHTTP(appPort, pathname, query, opts) {
return fetchViaHTTP(appPort, pathname, query, opts).then((res) => res.text())
}
export function fetchViaHTTP(appPort, pathname, query, opts) {
const url = `${pathname}${
typeof query === 'string' ? query : query ? `?${qs.stringify(query)}` : ''
}`
return fetch(getFullUrl(appPort, url), opts)
}
export function findPort() {
return getPort()
}
export function runNextCommand(argv, options = {}) {
const nextDir = path.dirname(require.resolve('next/package'))
const nextBin = path.join(nextDir, 'dist/bin/next')
const cwd = options.cwd || nextDir
// Let Next.js decide the environment
const env = {
...process.env,
...options.env,
NODE_ENV: '',
__NEXT_TEST_MODE: 'true',
}
return new Promise((resolve, reject) => {
console.log(`Running command "next ${argv.join(' ')}"`)
const instance = spawn(
'node',
[...(options.nodeArgs || []), '--no-deprecation', nextBin, ...argv],
{
...options.spawnOptions,
cwd,
env,
stdio: ['ignore', 'pipe', 'pipe'],
}
)
if (typeof options.instance === 'function') {
options.instance(instance)
}
let stderrOutput = ''
if (options.stderr) {
instance.stderr.on('data', function (chunk) {
stderrOutput += chunk
if (options.stderr === 'log') {
console.log(chunk.toString())
}
})
}
let stdoutOutput = ''
if (options.stdout) {
instance.stdout.on('data', function (chunk) {
stdoutOutput += chunk
if (options.stdout === 'log') {
console.log(chunk.toString())
}
})
}
instance.on('close', (code, signal) => {
if (
!options.stderr &&
!options.stdout &&
!options.ignoreFail &&
code !== 0
) {
return reject(new Error(`command failed with code ${code}`))
}
resolve({
code,
signal,
stdout: stdoutOutput,
stderr: stderrOutput,
})
})
instance.on('error', (err) => {
err.stdout = stdoutOutput
err.stderr = stderrOutput
reject(err)
})
})
}
export function runNextCommandDev(argv, stdOut, opts = {}) {
const nextDir = path.dirname(require.resolve('next/package'))
const nextBin = path.join(nextDir, 'dist/bin/next')
const cwd = opts.cwd || nextDir
const env = {
...process.env,
NODE_ENV: undefined,
__NEXT_TEST_MODE: 'true',
...opts.env,
}
const nodeArgs = opts.nodeArgs || []
return new Promise((resolve, reject) => {
const instance = spawn(
'node',
[...nodeArgs, '--no-deprecation', nextBin, ...argv],
{
cwd,
env,
}
)
let didResolve = false
function handleStdout(data) {
const message = data.toString()
const bootupMarkers = {
dev: /compiled successfully/i,
start: /started server/i,
}
if (
(opts.bootupMarker && opts.bootupMarker.test(message)) ||
bootupMarkers[opts.nextStart || stdOut ? 'start' : 'dev'].test(message)
) {
if (!didResolve) {
didResolve = true
resolve(stdOut ? message : instance)
}
}
if (typeof opts.onStdout === 'function') {
opts.onStdout(message)
}
if (opts.stdout !== false) {
process.stdout.write(message)
}
}
function handleStderr(data) {
const message = data.toString()
if (typeof opts.onStderr === 'function') {
opts.onStderr(message)
}
if (opts.stderr !== false) {
process.stderr.write(message)
}
}
instance.stdout.on('data', handleStdout)
instance.stderr.on('data', handleStderr)
instance.on('close', () => {
instance.stdout.removeListener('data', handleStdout)
instance.stderr.removeListener('data', handleStderr)
if (!didResolve) {
didResolve = true
resolve()
}
})
instance.on('error', (err) => {
reject(err)
})
})
}
// Launch the app in dev mode.
export function launchApp(dir, port, opts) {
return runNextCommandDev([dir, '-p', port], undefined, opts)
}
export function nextBuild(dir, args = [], opts = {}) {
return runNextCommand(['build', dir, ...args], opts)
}
export function nextExport(dir, { outdir }, opts = {}) {
return runNextCommand(['export', dir, '--outdir', outdir], opts)
}
export function nextExportDefault(dir, opts = {}) {
return runNextCommand(['export', dir], opts)
}
export function nextLint(dir, args = [], opts = {}) {
return runNextCommand(['lint', dir, ...args], opts)
}
export function nextStart(dir, port, opts = {}) {
return runNextCommandDev(['start', '-p', port, dir], undefined, {
...opts,
nextStart: true,
})
}
export function buildTS(args = [], cwd, env = {}) {
cwd = cwd || path.dirname(require.resolve('next/package'))
env = { ...process.env, NODE_ENV: undefined, ...env }
return new Promise((resolve, reject) => {
const instance = spawn(
'node',
['--no-deprecation', require.resolve('typescript/lib/tsc'), ...args],
{ cwd, env }
)
let output = ''
const handleData = (chunk) => {
output += chunk.toString()
}
instance.stdout.on('data', handleData)
instance.stderr.on('data', handleData)
instance.on('exit', (code) => {
if (code) {
return reject(new Error('exited with code: ' + code + '\n' + output))
}
resolve()
})
})
}
// Kill a launched app
export async function killApp(instance) {
await new Promise((resolve, reject) => {
treeKill(instance.pid, (err) => {
if (err) {
if (
process.platform === 'win32' &&
typeof err.message === 'string' &&
(err.message.includes(`no running instance of the task`) ||
err.message.includes(`not found`))
) {
// Windows throws an error if the process is already dead
//
// Command failed: taskkill /pid 6924 /T /F
// ERROR: The process with PID 6924 (child process of PID 6736) could not be terminated.
// Reason: There is no running instance of the task.
return resolve()
}
return reject(err)
}
resolve()
})
})
}
export async function startApp(app) {
await app.prepare()
const handler = app.getRequestHandler()
const server = http.createServer(handler)
server.__app = app
await promiseCall(server, 'listen')
return server
}
export async function stopApp(server) {
if (server.__app) {
await server.__app.close()
}
await promiseCall(server, 'close')
}
export function promiseCall(obj, method, ...args) {
return new Promise((resolve, reject) => {
const newArgs = [
...args,
function (err, res) {
if (err) return reject(err)
resolve(res)
},
]
obj[method](...newArgs)
})
}
export function waitFor(millis) {
return new Promise((resolve) => setTimeout(resolve, millis))
}
export async function startStaticServer(dir, notFoundFile, fixedPort) {
const app = express()
const server = http.createServer(app)
app.use(express.static(dir))
if (notFoundFile) {
app.use((req, res) => {
createReadStream(notFoundFile).pipe(res)
})
}
await promiseCall(server, 'listen', fixedPort)
return server
}
export async function startCleanStaticServer(dir) {
const app = express()
const server = http.createServer(app)
app.use(express.static(dir, { extensions: ['html'] }))
await promiseCall(server, 'listen')
return server
}
// check for content in 1 second intervals timing out after
// 30 seconds
export async function check(contentFn, regex, hardError = true) {
let content
let lastErr
for (let tries = 0; tries < 30; tries++) {
try {
content = await contentFn()
if (typeof regex === 'string') {
if (regex === content) {
return true
}
} else if (regex.test(content)) {
// found the content
return true
}
await waitFor(1000)
} catch (err) {
await waitFor(1000)
lastErr = err
}
}
console.error('TIMED OUT CHECK: ', { regex, content, lastErr })
if (hardError) {
throw new Error('TIMED OUT: ' + regex + '\n\n' + content)
}
return false
}
export class File {
constructor(path) {
this.path = path
this.originalContent = existsSync(this.path)
? readFileSync(this.path, 'utf8')
: null
}
write(content) {
if (!this.originalContent) {
this.originalContent = content
}
writeFileSync(this.path, content, 'utf8')
}
replace(pattern, newValue) {
const currentContent = readFileSync(this.path, 'utf8')
if (pattern instanceof RegExp) {
if (!pattern.test(currentContent)) {
throw new Error(
`Failed to replace content.\n\nPattern: ${pattern.toString()}\n\nContent: ${currentContent}`
)
}
} else if (typeof pattern === 'string') {
if (!currentContent.includes(pattern)) {
throw new Error(
`Failed to replace content.\n\nPattern: ${pattern}\n\nContent: ${currentContent}`
)
}
} else {
throw new Error(`Unknown replacement attempt type: ${pattern}`)
}
const newContent = currentContent.replace(pattern, newValue)
this.write(newContent)
}
delete() {
unlinkSync(this.path)
}
restore() {
this.write(this.originalContent)
}
}
export async function evaluate(browser, input) {
if (typeof input === 'function') {
const result = await browser.eval(input)
await new Promise((resolve) => setTimeout(resolve, 30))
return result
} else {
throw new Error(`You must pass a function to be evaluated in the browser.`)
}
}
export async function retry(fn, duration = 3000, interval = 500, description) {
if (duration % interval !== 0) {
throw new Error(
`invalid duration ${duration} and interval ${interval} mix, duration must be evenly divisible by interval`
)
}
for (let i = duration; i >= 0; i -= interval) {
try {
return await fn()
} catch (err) {
if (i === 0) {
console.error(
`Failed to retry${
description ? ` ${description}` : ''
} within ${duration}ms`
)
throw err
}
console.warn(
`Retrying${description ? ` ${description}` : ''} in ${interval}ms`
)
await waitFor(interval)
}
}
}
export async function hasRedbox(browser, expected = true) {
for (let i = 0; i < 30; i++) {
const result = await evaluate(browser, () => {
return Boolean(
[].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector(
'#nextjs__container_errors_label, #nextjs__container_build_error_label'
)
)
)
})
if (result === expected) {
return result
}
await waitFor(1000)
}
return false
}
export async function getRedboxHeader(browser) {
return retry(
() =>
evaluate(browser, () => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header'))
const root = portal.shadowRoot
return root
.querySelector('[data-nextjs-dialog-header]')
.innerText.replace(/__WEBPACK_DEFAULT_EXPORT__/, 'Unknown')
}),
3000,
500,
'getRedboxHeader'
)
}
export async function getRedboxSource(browser) {
return retry(
() =>
evaluate(browser, () => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector(
'#nextjs__container_errors_label, #nextjs__container_build_error_label'
)
)
const root = portal.shadowRoot
return root
.querySelector('[data-nextjs-codeframe], [data-nextjs-terminal]')
.innerText.replace(/__WEBPACK_DEFAULT_EXPORT__/, 'Unknown')
}),
3000,
500,
'getRedboxSource'
)
}
export async function getRedboxDescription(browser) {
return retry(
() =>
evaluate(browser, () => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p) =>
p.shadowRoot.querySelector('[data-nextjs-dialog-header]')
)
const root = portal.shadowRoot
return root
.querySelector('#nextjs__container_errors_desc')
.innerText.replace(/__WEBPACK_DEFAULT_EXPORT__/, 'Unknown')
}),
3000,
500,
'getRedboxDescription'
)
}
export function getBrowserBodyText(browser) {
return browser.eval('document.getElementsByTagName("body")[0].innerText')
}
export function normalizeRegEx(src) {
return new RegExp(src).source.replace(/\^\//g, '^\\/')
}
function readJson(path) {
return JSON.parse(readFileSync(path))
}
export function getBuildManifest(dir) {
return readJson(path.join(dir, '.next/build-manifest.json'))
}
export function getPageFileFromBuildManifest(dir, page) {
const buildManifest = getBuildManifest(dir)
const pageFiles = buildManifest.pages[page]
if (!pageFiles) {
throw new Error(`No files for page ${page}`)
}
const pageFile = pageFiles.find(
(file) =>
file.endsWith('.js') &&
file.includes(`pages${page === '' ? '/index' : page}`)
)
if (!pageFile) {
throw new Error(`No page file for page ${page}`)
}
return pageFile
}
export function readNextBuildClientPageFile(appDir, page) {
const pageFile = getPageFileFromBuildManifest(appDir, page)
return readFileSync(path.join(appDir, '.next', pageFile), 'utf8')
}
export function getPagesManifest(dir) {
const serverFile = path.join(dir, '.next/server/pages-manifest.json')
if (existsSync(serverFile)) {
return readJson(serverFile)
}
return readJson(path.join(dir, '.next/serverless/pages-manifest.json'))
}
export function updatePagesManifest(dir, content) {
const serverFile = path.join(dir, '.next/server/pages-manifest.json')
if (existsSync(serverFile)) {
return writeFile(serverFile, content)
}
return writeFile(
path.join(dir, '.next/serverless/pages-manifest.json'),
content
)
}
export function getPageFileFromPagesManifest(dir, page) {
const pagesManifest = getPagesManifest(dir)
const pageFile = pagesManifest[page]
if (!pageFile) {
throw new Error(`No file for page ${page}`)
}
return pageFile
}
export function readNextBuildServerPageFile(appDir, page) {
const pageFile = getPageFileFromPagesManifest(appDir, page)
return readFileSync(path.join(appDir, '.next', 'server', pageFile), 'utf8')
}