forked from vercel/next.js
/
index.test.js
534 lines (467 loc) · 16.1 KB
/
index.test.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
/* eslint-env jest */
/* global jasmine */
import cheerio from 'cheerio'
import escapeRegex from 'escape-string-regexp'
import fs from 'fs-extra'
import {
check,
fetchViaHTTP,
findPort,
getBrowserBodyText,
killApp,
launchApp,
nextBuild,
nextStart,
normalizeRegEx,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js')
let app
let appPort
let buildId
let stderr
const expectedManifestRoutes = () => [
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/index.json$`
),
page: '/',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/another.json$`
),
page: '/another',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog.json$`
),
page: '/blog',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`
),
page: '/blog/[post]/[comment]',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/catchall\\/(.+?)\\.json$`
),
page: '/catchall/[...path]',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/custom-cache.json$`
),
page: '/custom-cache',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/default-revalidate.json$`
),
page: '/default-revalidate',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/enoent.json$`
),
page: '/enoent',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/invalid-keys.json$`
),
page: '/invalid-keys',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/non-json.json$`
),
page: '/non-json',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/something.json$`
),
page: '/something',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/user\\/([^\\/]+?)\\/profile\\.json$`
),
page: '/user/[user]/profile',
},
]
const navigateTest = (dev = false) => {
it('should navigate between pages successfully', async () => {
const toBuild = [
'/',
'/another',
'/something',
'/normal',
'/blog/post-1',
'/blog/post-1/comment-1',
]
await Promise.all(toBuild.map(pg => renderViaHTTP(appPort, pg)))
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// hydration
await waitFor(2500)
// go to /another
async function goFromHomeToAnother() {
await browser.elementByCss('#another').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
}
await goFromHomeToAnother()
// go to /
async function goFromAnotherToHome() {
await browser.eval('window.didTransition = 1')
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#another')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
}
await goFromAnotherToHome()
await goFromHomeToAnother()
const snapTime = await browser.elementByCss('#anotherTime').text()
// Re-visit page
await goFromAnotherToHome()
await goFromHomeToAnother()
const nextTime = await browser.elementByCss('#anotherTime').text()
expect(snapTime).not.toMatch(nextTime)
// Reset to Home for next test
await goFromAnotherToHome()
// go to /something
await browser.elementByCss('#something').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#post-1')
// go to /blog/post-1
await browser.elementByCss('#post-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Post:.*?post-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /blog/post-1/comment-1
await browser.elementByCss('#comment-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p:nth-child(2)').text()
expect(text).toMatch(/Comment:.*?comment-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
await browser.close()
})
}
const runTests = (dev = false) => {
navigateTest(dev)
it('should SSR normal page correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/hello.*?world/)
})
it('should SSR getServerSideProps page correctly', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
expect(html).toMatch(/Post:.*?post-1/)
})
it('should handle throw ENOENT correctly', async () => {
const res = await fetchViaHTTP(appPort, '/enoent')
const html = await res.text()
if (dev) {
expect(html).toContain('oof')
} else {
expect(res.status).toBe(500)
expect(html).toContain('Internal Server Error')
expect(html).not.toContain('This page could not be found')
}
})
it('should have gssp in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gssp).toBe(true)
})
it('should not have gssp in __NEXT_DATA__ for non-GSSP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect('gssp' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should supply query values SSR', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1?hello=world')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' })
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world', post: 'post-1' })
})
it('should supply params values for catchall correctly', async () => {
const html = await renderViaHTTP(appPort, '/catchall/first')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ path: ['first'] })
const query = $('#query').text()
expect(JSON.parse(query)).toEqual({ path: ['first'] })
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/catchall/first.json`)
)
expect(data.pageProps.params).toEqual({ path: ['first'] })
})
it('should return data correctly', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/something.json`)
)
expect(data.pageProps.world).toBe('world')
})
it('should pass query for data request', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${buildId}/something.json?another=thing`
)
)
expect(data.pageProps.query.another).toBe('thing')
})
it('should return data correctly for dynamic page', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/blog/post-1.json`)
)
expect(data.pageProps.post).toBe('post-1')
})
it('should navigate to a normal page and back', async () => {
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
await browser.elementByCss('#normal').click()
await browser.waitForElementByCss('#normal-text')
text = await browser.elementByCss('#normal-text').text()
expect(text).toMatch(/a normal page/)
})
it('should provide correct query value for dynamic page', async () => {
const html = await renderViaHTTP(
appPort,
'/blog/post-1?post=something-else'
)
const $ = cheerio.load(html)
const query = JSON.parse($('#query').text())
expect(query.post).toBe('post-1')
})
it('should parse query values on mount correctly', async () => {
const browser = await webdriver(appPort, '/blog/post-1?another=value')
await waitFor(2000)
const text = await browser.elementByCss('#query').text()
expect(text).toMatch(/another.*?value/)
expect(text).toMatch(/post.*?post-1/)
})
it('should pass query for data request on navigation', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval('window.beforeNav = true')
await browser.elementByCss('#something-query').click()
await browser.waitForElementByCss('#initial-query')
const query = JSON.parse(
await browser.elementByCss('#initial-query').text()
)
expect(await browser.eval('window.beforeNav')).toBe(true)
expect(query.another).toBe('thing')
})
it('should reload page on failed data request', async () => {
const browser = await webdriver(appPort, '/')
await waitFor(500)
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-post').click()
await waitFor(1000)
expect(await browser.eval('window.beforeClick')).not.toBe('abc')
})
it('should always call getServerSideProps without caching', async () => {
const initialRes = await fetchViaHTTP(appPort, '/something')
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
const newRes = await fetchViaHTTP(appPort, '/something')
const newHtml = await newRes.text()
expect(newHtml).toMatch(/hello.*?world/)
expect(initialHtml !== newHtml).toBe(true)
const newerRes = await fetchViaHTTP(appPort, '/something')
const newerHtml = await newerRes.text()
expect(newerHtml).toMatch(/hello.*?world/)
expect(newHtml !== newerHtml).toBe(true)
})
it('should not re-call getServerSideProps when updating query', async () => {
const browser = await webdriver(appPort, '/something?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world' })
const {
props: {
pageProps: { random: initialRandom },
},
} = await browser.eval('window.__NEXT_DATA__')
const curRandom = await browser.elementByCss('#random').text()
expect(curRandom).toBe(initialRandom + '')
})
if (dev) {
it('should not show warning from url prop being returned', async () => {
const urlPropPage = join(appDir, 'pages/url-prop.js')
await fs.writeFile(
urlPropPage,
`
export async function getServerSideProps() {
return {
props: {
url: 'something'
}
}
}
export default ({ url }) => <p>url: {url}</p>
`
)
const html = await renderViaHTTP(appPort, '/url-prop')
await fs.remove(urlPropPage)
expect(stderr).not.toMatch(
/The prop `url` is a reserved prop in Next.js for legacy reasons and will be overridden on page \/url-prop/
)
expect(html).toMatch(/url:.*?something/)
})
it('should show error for extra keys returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/invalid-keys')
expect(html).toContain(
`Additional keys were returned from \`getServerSideProps\`. Properties intended for your component must be nested under the \`props\` key, e.g.:`
)
expect(html).toContain(
`Keys that need to be moved: world, query, params, time, random`
)
})
it('should show error for invalid JSON returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/non-json')
expect(html).toContain(
'Error serializing `.time` returned from `getServerSideProps`'
)
})
it('should show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#non-json').click()
await check(
() => getBrowserBodyText(browser),
/Error serializing `.time` returned from `getServerSideProps`/
)
})
} else {
it('should not fetch data on mount', async () => {
const browser = await webdriver(appPort, '/blog/post-100')
await browser.eval('window.thisShouldStay = true')
await waitFor(2 * 1000)
const val = await browser.eval('window.thisShouldStay')
expect(val).toBe(true)
})
it('should output routes-manifest correctly', async () => {
const { dataRoutes } = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
)
for (const route of dataRoutes) {
route.dataRouteRegex = normalizeRegEx(route.dataRouteRegex)
}
expect(dataRoutes).toEqual(expectedManifestRoutes())
})
it('should set default caching header', async () => {
const resPage = await fetchViaHTTP(appPort, `/something`)
expect(resPage.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
const resData = await fetchViaHTTP(
appPort,
`/_next/data/${buildId}/something.json`
)
expect(resData.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
})
it('should respect custom caching header', async () => {
const resPage = await fetchViaHTTP(appPort, `/custom-cache`)
expect(resPage.headers.get('cache-control')).toBe('public, max-age=3600')
const resData = await fetchViaHTTP(
appPort,
`/_next/data/${buildId}/custom-cache.json`
)
expect(resData.headers.get('cache-control')).toBe('public, max-age=3600')
})
it('should not show error for invalid JSON returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/non-json')
expect(html).not.toContain('Error serializing')
expect(html).toContain('hello ')
})
it('should not show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#non-json').click()
await check(() => getBrowserBodyText(browser), /hello /)
})
}
}
describe('getServerSideProps', () => {
describe('dev mode', () => {
beforeAll(async () => {
stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStderr(msg) {
stderr += msg
},
})
buildId = 'development'
})
afterAll(() => killApp(app))
runTests(true)
})
describe('serverless mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`module.exports = { target: 'serverless' }`,
'utf8'
)
await nextBuild(appDir)
stderr = ''
appPort = await findPort()
app = await nextStart(appDir, appPort, {
onStderr(msg) {
stderr += msg
},
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(() => killApp(app))
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await fs.remove(nextConfig)
await nextBuild(appDir, [], { stdout: true })
appPort = await findPort()
app = await nextStart(appDir, appPort)
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(() => killApp(app))
runTests()
})
})