forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.test.js
1317 lines (1155 loc) · 41.4 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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-env jest */
/* global browserName */
import cheerio from 'cheerio'
import fs, { existsSync } from 'fs-extra'
import globOriginal from 'glob'
import {
renderViaHTTP,
waitFor,
getPageFileFromPagesManifest,
check,
nextBuild,
nextStart,
findPort,
killApp,
fetchViaHTTP,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import {
BUILD_MANIFEST,
PAGES_MANIFEST,
REACT_LOADABLE_MANIFEST,
} from 'next/constants'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { join, sep } from 'path'
import dynamicImportTests from './dynamic'
import processEnv from './process-env'
import security from './security'
import { promisify } from 'util'
import { error } from 'console'
const glob = promisify(globOriginal)
const appDir = join(__dirname, '../')
let appPort
let app
const context = {}
describe('Production Usage', () => {
let output = ''
beforeAll(async () => {
let opts = {
stderr: true,
stdout: true,
}
if (process.env.TEST_WASM) {
opts.env = {
NODE_OPTIONS: '--no-addons',
}
}
const result = await nextBuild(appDir, undefined, opts)
appPort = await findPort()
context.appPort = appPort
app = await nextStart(appDir, appPort, { cwd: appDir })
output = (result.stderr || '') + (result.stdout || '')
if (result.code !== 0) {
error(output)
throw new Error(`Failed to build, exited with code ${result.code}`)
} else {
// Note: jest captures calls to console and only emits when there's assertion fails,
// so this won't log anything for normal test execution path.
console.log(output)
}
})
afterAll(async () => {
await killApp(app)
})
it('should navigate through history after query update', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval('window.next.router.push("/about?a=b")')
await browser.waitForElementByCss('.about-page')
await browser.waitForCondition(`!!window.next.router.isReady`)
await browser.refresh()
await browser.waitForCondition(`!!window.next.router.isReady`)
await browser.back()
await browser.waitForElementByCss('.index-page')
await browser.forward()
await browser.waitForElementByCss('.about-page')
await browser.back()
await browser.waitForElementByCss('.index-page')
await browser.refresh()
await browser.waitForCondition(`!!window.next.router.isReady`)
await browser.forward()
await browser.waitForElementByCss('.about-page')
})
it('should not show target deprecation warning', () => {
expect(output).not.toContain(
'The `target` config is deprecated and will be removed in a future version'
)
})
it('should respond with 405 for POST to static page', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
method: 'POST',
})
expect(res.status).toBe(405)
expect(await res.text()).toContain('Method Not Allowed')
})
it('should contain generated page count in output', async () => {
const pageCount = 40
expect(output).toContain(`Generating static pages (0/${pageCount})`)
expect(output).toContain(
`Generating static pages (${pageCount}/${pageCount})`
)
// we should only have 4 segments and the initial message logged out
expect(output.match(/Generating static pages/g).length).toBe(5)
})
it('should output traces', async () => {
const serverTrace = await fs.readJSON(
join(appDir, '.next/next-server.js.nft.json')
)
expect(serverTrace.version).toBe(1)
expect(
serverTrace.files.some((file) =>
file.includes('next/dist/server/send-payload/index.js')
)
).toBe(true)
const repoRoot = join(__dirname, '../../../../')
expect(
serverTrace.files.some((file) => {
const fullPath = join(__dirname, '../.next', file)
if (!fullPath.startsWith(repoRoot)) {
console.error(`Found next-server trace file outside repo root`, {
repoRoot,
fullPath,
file,
})
return true
}
return false
})
).toBe(false)
expect(
serverTrace.files.some((file) =>
file.includes('next/dist/shared/lib/page-path/normalize-page-path.js')
)
).toBe(true)
expect(
serverTrace.files.some((file) =>
file.includes('next/dist/server/render.js')
)
).toBe(true)
expect(
serverTrace.files.some((file) =>
file.includes('next/dist/server/load-components.js')
)
).toBe(true)
if (process.platform !== 'win32') {
expect(
serverTrace.files.some((file) =>
file.includes('next/dist/compiled/webpack/bundle5.js')
)
).toBe(false)
expect(
serverTrace.files.some((file) => file.includes('node_modules/sharp'))
).toBe(false)
}
const checks = [
{
page: '/_app',
tests: [
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
],
notTests: [/\0/, /\?/, /!/],
},
{
page: '/client-error',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/next/,
/next\/link\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
/next\/error\.js/,
],
notTests: [/\0/, /\?/, /!/],
},
{
page: '/dynamic',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/next/,
/next\/link\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
],
notTests: [/\0/, /\?/, /!/],
},
{
page: '/index',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/next/,
/next\/link\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
/node_modules\/nanoid\/index\.js/,
/node_modules\/nanoid\/url-alphabet\/index\.js/,
/node_modules\/es5-ext\/array\/#\/clear\.js/,
],
notTests: [
/next\/dist\/pages\/_error\.js/,
/next\/error\.js/,
/\0/,
/\?/,
/!/,
],
},
{
page: '/counter',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/react\/cjs\/react\.development\.js/,
/node_modules\/next/,
/next\/router\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
],
notTests: [/\0/, /\?/, /!/],
},
{
page: '/next-import',
tests: [
/webpack-runtime\.js/,
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.min\.js/,
/node_modules\/next/,
/next\/link\.js/,
/next\/dist\/shared\/lib\/router\/utils\/resolve-rewrites\.js/,
],
notTests: [
/next\/dist\/server\/next\.js/,
/next\/dist\/bin/,
/\0/,
/\?/,
/!/,
],
},
{
page: '/api',
tests: [/webpack-runtime\.js/, /\/logo\.module\.css/],
notTests: [
/next\/dist\/server\/next\.js/,
/next\/dist\/bin/,
/\0/,
/\?/,
/!/,
],
},
{
page: '/api/readfile-dirname',
tests: [/webpack-api-runtime\.js/, /static\/data\/item\.txt/],
notTests: [
/next\/dist\/server\/next\.js/,
/next\/dist\/bin/,
/\0/,
/\?/,
/!/,
],
},
{
page: '/api/readfile-processcwd',
tests: [/webpack-api-runtime\.js/, /static\/data\/item\.txt/],
notTests: [
/next\/dist\/server\/next\.js/,
/next\/dist\/bin/,
/\0/,
/\?/,
/!/,
],
},
]
for (const check of checks) {
const contents = await fs.readFile(
join(appDir, '.next/server/pages/', check.page + '.js.nft.json'),
'utf8'
)
const { version, files } = JSON.parse(contents)
expect(version).toBe(1)
expect([...new Set(files)].length).toBe(files.length)
expect(
check.tests.every((item) => {
if (files.some((file) => item.test(file))) {
return true
}
console.error(`Failed to find ${item} in`, files)
return false
})
).toBe(true)
if (sep === '/') {
expect(
check.notTests.some((item) => {
if (files.some((file) => item.test(file))) {
console.error(`Found unexpected ${item} in`, files)
return true
}
return false
})
).toBe(false)
}
}
})
it('should not contain currentScript usage for publicPath', async () => {
const globResult = await glob('webpack-*.js', {
cwd: join(appDir, '.next/static/chunks'),
})
if (!globResult || globResult.length !== 1) {
throw new Error('could not find webpack-hash.js chunk')
}
const content = await fs.readFile(
join(appDir, '.next/static/chunks', globResult[0]),
'utf8'
)
expect(content).not.toContain('.currentScript')
})
it('should not contain amp, rsc APIs in main chunk', async () => {
const globResult = await glob('main-*.js', {
cwd: join(appDir, '.next/static/chunks'),
})
if (!globResult || globResult.length !== 1) {
throw new Error('could not find main js chunk')
}
const content = await fs.readFile(
join(appDir, '.next/static/chunks', globResult[0]),
'utf8'
)
expect(content).not.toContain('useAmp')
expect(content).not.toContain('useRefreshRoot')
})
describe('With basic usage', () => {
it('should render the page', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
})
if (browserName === 'internet explorer') {
it('should handle bad Promise polyfill', async () => {
const browser = await webdriver(appPort, '/bad-promise')
expect(await browser.eval('window.didRender')).toBe(true)
})
it('should polyfill RegExp successfully', async () => {
const browser = await webdriver(appPort, '/regexp-polyfill')
expect(await browser.eval('window.didRender')).toBe(true)
// wait a second for the script to be loaded
await waitFor(1000)
expect(await browser.eval('window.isSticky')).toBe(true)
expect(await browser.eval('window.isMatch1')).toBe(true)
expect(await browser.eval('window.isMatch2')).toBe(false)
})
}
it('should polyfill Node.js modules', async () => {
const browser = await webdriver(appPort, '/node-browser-polyfills')
await browser.waitForCondition('window.didRender')
const data = await browser
.waitForElementByCss('#node-browser-polyfills')
.text()
const parsedData = JSON.parse(data)
expect(parsedData.vm).toBe(105)
expect(parsedData.hash).toBe(
'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
)
expect(parsedData.path).toBe('/hello/world/test.txt')
expect(parsedData.buffer).toBe('hello world')
expect(parsedData.stream).toBe(true)
})
it('should allow etag header support', async () => {
const url = `http://localhost:${appPort}`
const etag = (await fetchViaHTTP(url, '/')).headers.get('ETag')
const headers = { 'If-None-Match': etag }
const res2 = await fetchViaHTTP(url, '/', undefined, { headers })
expect(res2.status).toBe(304)
})
it('should allow etag header support with getStaticProps', async () => {
const url = `http://localhost:${appPort}`
const etag = (await fetchViaHTTP(url, '/fully-static')).headers.get(
'ETag'
)
const headers = { 'If-None-Match': etag }
const res2 = await fetchViaHTTP(url, '/fully-static', undefined, {
headers,
})
expect(res2.status).toBe(304)
})
// TODO: should we generate weak etags for streaming getServerSideProps?
// this is currently not expected to work with react-18
it.skip('should allow etag header support with getServerSideProps', async () => {
const url = `http://localhost:${appPort}`
const etag = (await fetchViaHTTP(url, '/fully-dynamic')).headers.get(
'ETag'
)
const headers = { 'If-None-Match': etag }
const res2 = await fetchViaHTTP(url, '/fully-dynamic', undefined, {
headers,
})
expect(res2.status).toBe(304)
})
it('should have X-Powered-By header support', async () => {
const url = `http://localhost:${appPort}`
const header = (await fetchViaHTTP(url, '/')).headers.get('X-Powered-By')
expect(header).toBe('Next.js')
})
it('should render 404 for routes that do not exist', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, '/abcdefghijklmno')
const text = await res.text()
const $html = cheerio.load(text)
expect($html('html').text()).toMatch(/404/)
expect(text).toMatch(/"statusCode":404/)
expect(res.status).toBe(404)
})
it('should render 404 for /_next/static route', async () => {
const html = await renderViaHTTP(appPort, '/_next/static')
expect(html).toMatch(/This page could not be found/)
})
it('should render 200 for POST on page', async () => {
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
'/fully-dynamic',
undefined,
{
method: 'POST',
}
)
expect(res.status).toBe(200)
})
it('should render 404 for POST on missing page', async () => {
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
'/fake-page',
undefined,
{
method: 'POST',
}
)
expect(res.status).toBe(404)
})
it('should render 404 for _next routes that do not exist', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, '/_next/abcdef')
expect(res.status).toBe(404)
})
it('should render 404 even if the HTTP method is not GET or HEAD', async () => {
const url = `http://localhost:${appPort}`
const methods = ['POST', 'PUT', 'DELETE']
for (const method of methods) {
const res = await fetchViaHTTP(url, '/_next/abcdef', undefined, {
method,
})
expect(res.status).toBe(404)
}
})
it('should render 404 for dotfiles in /static', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, '/static/.env')
expect(res.status).toBe(404)
})
it('should return 405 method on static then GET and HEAD', async () => {
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
'/static/data/item.txt',
undefined,
{
method: 'POST',
}
)
expect(res.headers.get('allow').includes('GET')).toBe(true)
expect(res.status).toBe(405)
})
it('should return 412 on static file when If-Unmodified-Since is provided and file is modified', async () => {
const buildManifest = require(join(
__dirname,
'../.next/build-manifest.json'
))
const files = buildManifest.pages['/']
for (const file of files) {
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
`/_next/${file}`,
undefined,
{
method: 'GET',
headers: { 'if-unmodified-since': 'Fri, 12 Jul 2019 20:00:13 GMT' },
}
)
expect(res.status).toBe(412)
}
})
it('should return 200 on static file if If-Unmodified-Since is invalid date', async () => {
const buildManifest = require(join(
__dirname,
'../.next/build-manifest.json'
))
const files = buildManifest.pages['/']
for (const file of files) {
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
`/_next/${file}`,
undefined,
{
method: 'GET',
headers: { 'if-unmodified-since': 'nextjs' },
}
)
expect(res.status).toBe(200)
}
})
it('should set Content-Length header', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, '/')
expect(res.headers.get('Content-Length')).toBeDefined()
})
it('should set Cache-Control header', async () => {
const buildManifest = require(join('../.next', BUILD_MANIFEST))
const reactLoadableManifest = require(join(
'../.next',
REACT_LOADABLE_MANIFEST
))
const url = `http://localhost:${appPort}`
const resources = new Set()
const manifestKey = Object.keys(reactLoadableManifest).find((item) => {
return item
.replace(/\\/g, '/')
.endsWith('dynamic/css.js -> ../../components/dynamic-css/with-css')
})
// test dynamic chunk
reactLoadableManifest[manifestKey].files.forEach((f) => {
resources.add('/' + f)
})
// test main.js runtime etc
for (const item of buildManifest.pages['/']) {
resources.add('/' + item)
}
const cssStaticAssets = await recursiveReadDir(
join(__dirname, '..', '.next', 'static'),
/\.css$/
)
expect(cssStaticAssets.length).toBeGreaterThanOrEqual(1)
expect(cssStaticAssets[0]).toMatch(/[\\/]css[\\/]/)
const mediaStaticAssets = await recursiveReadDir(
join(__dirname, '..', '.next', 'static'),
/\.svg$/
)
expect(mediaStaticAssets.length).toBeGreaterThanOrEqual(1)
expect(mediaStaticAssets[0]).toMatch(/[\\/]media[\\/]/)
;[...cssStaticAssets, ...mediaStaticAssets].forEach((asset) => {
resources.add(`/static${asset.replace(/\\+/g, '/')}`)
})
const responses = await Promise.all(
[...resources].map((resource) =>
fetchViaHTTP(url, join('/_next', resource))
)
)
responses.forEach((res) => {
try {
expect(res.headers.get('Cache-Control')).toBe(
'public, max-age=31536000, immutable'
)
} catch (err) {
err.message = res.url + ' ' + err.message
throw err
}
})
})
it('should set correct Cache-Control header for static 404s', async () => {
// this is to fix where 404 headers are set to 'public, max-age=31536000, immutable'
const res = await fetchViaHTTP(
`http://localhost:${appPort}`,
`/_next//static/common/bad-static.js`
)
expect(res.status).toBe(404)
expect(res.headers.get('Cache-Control')).toBe(
'no-cache, no-store, max-age=0, must-revalidate'
)
})
it('should block special pages', async () => {
const urls = ['/_document', '/_app']
for (const url of urls) {
const html = await renderViaHTTP(appPort, url)
expect(html).toMatch(/404/)
}
})
it('should not contain customServer in NEXT_DATA', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect('customServer' in JSON.parse($('#__NEXT_DATA__').text())).toBe(
false
)
})
})
describe('API routes', () => {
it('should work with pages/api/index.js', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, `/api`)
const body = await res.text()
expect(body).toEqual('API index works')
})
it('should work with pages/api/hello.js', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, `/api/hello`)
const body = await res.text()
expect(body).toEqual('API hello works')
})
// Today, `__dirname` usage fails because Next.js moves the source file
// to .next/server/pages/api but it doesn't move the asset file.
// In the future, it would be nice to make `__dirname` work too.
it('does not work with pages/api/readfile-dirname.js', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, `/api/readfile-dirname`)
expect(res.status).toBe(500)
})
it('should work with pages/api/readfile-processcwd.js', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, `/api/readfile-processcwd`)
const body = await res.text()
expect(body).toBe('item')
})
it('should work with dynamic params and search string', async () => {
const url = `http://localhost:${appPort}`
const res = await fetchViaHTTP(url, `/api/post-1?val=1`)
const body = await res.json()
expect(body).toEqual({ val: '1', post: 'post-1' })
})
})
describe('With navigation', () => {
it('should navigate via client side', async () => {
const browser = await webdriver(appPort, '/')
const text = await browser
.elementByCss('a')
.click()
.waitForElementByCss('.about-page')
.elementByCss('div')
.text()
expect(text).toBe('About Page')
await browser.close()
})
it('should navigate to nested index via client side', async () => {
const browser = await webdriver(appPort, '/another')
await browser.eval('window.beforeNav = 1')
const text = await browser
.elementByCss('a')
.click()
.waitForElementByCss('.index-page')
.elementByCss('p')
.text()
expect(text).toBe('Hello World')
expect(await browser.eval('window.beforeNav')).toBe(1)
await browser.close()
})
it('should set title by routeChangeComplete event', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(function setup() {
window.next.router.events.on(
'routeChangeComplete',
function handler(url) {
window.routeChangeTitle = document.title
window.routeChangeUrl = url
}
)
window.next.router.push('/with-title')
})
await browser.waitForElementByCss('#with-title')
const title = await browser.eval(`window.routeChangeTitle`)
const url = await browser.eval(`window.routeChangeUrl`)
expect(title).toBe('hello from title')
expect(url).toBe('/with-title')
})
it('should reload page successfully (on bad link)', async () => {
const browser = await webdriver(appPort, '/to-nonexistent')
await browser.eval(function setup() {
window.__DATA_BE_GONE = 'true'
})
await browser.waitForElementByCss('#to-nonexistent-page')
await browser.click('#to-nonexistent-page')
await browser.waitForElementByCss('.about-page')
const oldData = await browser.eval(`window.__DATA_BE_GONE`)
expect(oldData).toBeFalsy()
})
it('should reload page successfully (on bad data fetch)', async () => {
const browser = await webdriver(appPort, '/to-shadowed-page')
await browser.eval(function setup() {
window.__DATA_BE_GONE = 'true'
})
await browser.waitForElementByCss('#to-shadowed-page').click()
await browser.waitForElementByCss('.about-page')
const oldData = await browser.eval(`window.__DATA_BE_GONE`)
expect(oldData).toBeFalsy()
})
})
it('should navigate to external site and back', async () => {
const browser = await webdriver(appPort, '/external-and-back')
const initialText = await browser.elementByCss('p').text()
expect(initialText).toBe('server')
await browser
.elementByCss('a')
.click()
.waitForElementByCss('input')
.back()
.waitForElementByCss('p')
await waitFor(1000)
const newText = await browser.elementByCss('p').text()
expect(newText).toBe('server')
})
it('should navigate to page with CSS and back', async () => {
const browser = await webdriver(appPort, '/css-and-back')
const initialText = await browser.elementByCss('p').text()
expect(initialText).toBe('server')
await browser
.elementByCss('a')
.click()
.waitForElementByCss('input')
.back()
.waitForElementByCss('p')
await waitFor(1000)
const newText = await browser.elementByCss('p').text()
expect(newText).toBe('client')
})
it('should navigate to external site and back (with query)', async () => {
const browser = await webdriver(appPort, '/external-and-back?hello=world')
const initialText = await browser.elementByCss('p').text()
expect(initialText).toBe('server')
await browser
.elementByCss('a')
.click()
.waitForElementByCss('input')
.back()
.waitForElementByCss('p')
await waitFor(1000)
const newText = await browser.elementByCss('p').text()
expect(newText).toBe('server')
})
it('should change query correctly', async () => {
const browser = await webdriver(appPort, '/query?id=0')
let id = await browser.elementByCss('#q0').text()
expect(id).toBe('0')
await browser.elementByCss('#first').click().waitForElementByCss('#q1')
id = await browser.elementByCss('#q1').text()
expect(id).toBe('1')
await browser.elementByCss('#second').click().waitForElementByCss('#q2')
id = await browser.elementByCss('#q2').text()
expect(id).toBe('2')
})
describe('Runtime errors', () => {
it('should render a server side error on the client side', async () => {
const browser = await webdriver(appPort, '/error-in-ssr-render')
await waitFor(2000)
const text = await browser.elementByCss('body').text()
// this makes sure we don't leak the actual error to the client side in production
expect(text).toMatch(/Internal Server Error\./)
const headingText = await browser.elementByCss('h1').text()
// This makes sure we render statusCode on the client side correctly
expect(headingText).toBe('500')
await browser.close()
})
it('should render a client side component error', async () => {
const browser = await webdriver(appPort, '/error-in-browser-render')
await waitFor(2000)
const text = await browser.elementByCss('body').text()
expect(text).toMatch(
/Application error: a client-side exception has occurred/
)
await browser.close()
})
it('should call getInitialProps on _error page during a client side component error', async () => {
const browser = await webdriver(
appPort,
'/error-in-browser-render-status-code'
)
await waitFor(2000)
const text = await browser.elementByCss('body').text()
expect(text).toMatch(/This page could not be found\./)
await browser.close()
})
})
describe('Misc', () => {
it('should handle already finished responses', async () => {
const html = await renderViaHTTP(appPort, '/finish-response')
expect(html).toBe('hi')
})
it('should allow to access /static/ and /_next/', async () => {
// This is a test case which prevent the following issue happening again.
// See: https://github.com/vercel/next.js/issues/2617
await renderViaHTTP(appPort, '/_next/')
await renderViaHTTP(appPort, '/static/')
const data = await renderViaHTTP(appPort, '/static/data/item.txt')
expect(data).toBe('item')
})
it('Should allow access to public files', async () => {
const data = await renderViaHTTP(appPort, '/data/data.txt')
const file = await renderViaHTTP(appPort, '/file')
const legacy = await renderViaHTTP(appPort, '/static/legacy.txt')
expect(data).toBe('data')
expect(file).toBe('test')
expect(legacy).toMatch(`new static folder`)
})
// TODO: do we want to normalize this for firefox? It seems in
// the latest version of firefox the window state is not reset
// when navigating back from a hard navigation. This might be
// a bug as other browsers do not behave this way.
if (browserName !== 'firefox') {
it('should reload the page on page script error', async () => {
const browser = await webdriver(appPort, '/counter')
const counter = await browser
.elementByCss('#increase')
.click()
.click()
.elementByCss('#counter')
.text()
expect(counter).toBe('Counter: 2')
// When we go to the 404 page, it'll do a hard reload.
// So, it's possible for the front proxy to load a page from another zone.
// Since the page is reloaded, when we go back to the counter page again,
// previous counter value should be gone.
const counterAfter404Page = await browser
.elementByCss('#no-such-page')
.click()
.waitForElementByCss('h1')
.back()
.waitForElementByCss('#counter-page')
.elementByCss('#counter')
.text()
expect(counterAfter404Page).toBe('Counter: 0')
await browser.close()
})
}
it('should have default runtime values when not defined', async () => {
const html = await renderViaHTTP(appPort, '/runtime-config')
expect(html).toMatch(/found public config/)
expect(html).toMatch(/found server config/)
})
it('should not have runtimeConfig in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/runtime-config')
const $ = cheerio.load(html)
const script = $('#__NEXT_DATA__').html()
expect(script).not.toMatch(/runtimeConfig/)
})
it('should add autoExport for auto pre-rendered pages', async () => {
for (const page of ['/', '/about']) {
const html = await renderViaHTTP(appPort, page)
const $ = cheerio.load(html)
const data = JSON.parse($('#__NEXT_DATA__').html())
expect(data.autoExport).toBe(true)
}
})
it('should not add autoExport for non pre-rendered pages', async () => {
for (const page of ['/query']) {
const html = await renderViaHTTP(appPort, page)
const $ = cheerio.load(html)
const data = JSON.parse($('#__NEXT_DATA__').html())
expect(!!data.autoExport).toBe(false)
}
})
it('should add prefetch tags when Link prefetch prop is used', async () => {
const browser = await webdriver(appPort, '/prefetch')
if (browserName === 'internet explorer') {
// IntersectionObserver isn't present so we need to trigger manually
await waitFor(1000)
await browser.eval(`(function() {
window.next.router.prefetch('/')
window.next.router.prefetch('/process-env')
window.next.router.prefetch('/counter')
window.next.router.prefetch('/about')
})()`)
}
await waitFor(2000)
if (browserName === 'safari') {
const elements = await browser.elementsByCss('link[rel=preload]')
// optimized preloading uses defer instead of preloading and prefetches
// aren't generated client-side since safari does not support prefetch
expect(elements.length).toBe(0)
} else {
const elements = await browser.elementsByCss('link[rel=prefetch]')
expect(elements.length).toBe(4)