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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
/* eslint-env jest */

import {
  waitFor,
  check,
  retry,
  getRedboxTotalErrorCount,
} from 'next-test-utils'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'

describe('Client Navigation', () => {
  const { isTurbopack, next } = nextTestSetup({
    files: path.join(__dirname, 'fixture'),
    env: {
      TEST_STRICT_NEXT_HEAD: String(true),
    },
  })

  describe('with empty getInitialProps()', () => {
    it('should render a redbox', async () => {
      const pageErrors: unknown[] = []
      const browser = await next.browser('/nav', {
        beforePageLoad: (page) => {
          page.on('pageerror', (error: unknown) => {
            pageErrors.push(error)
          })
        },
      })
      await browser.elementByCss('#empty-props').click()
      await expect(browser).toDisplayRedbox(`
         {
           "description": ""EmptyInitialPropsPage.getInitialProps()" should resolve to an object. But found "null" instead.",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": null,
           "stack": [],
         }
        `)
      expect(pageErrors).toEqual([
        expect.objectContaining({
          message:
            '"EmptyInitialPropsPage.getInitialProps()" should resolve to an object. But found "null" instead.',
        }),
      ])
    })
  })

  describe('with the current url', () => {
    it('should reload the page', async () => {
      const browser = await next.browser('/nav/self-reload')
      const defaultCount = await browser.elementByCss('p').text()
      expect(defaultCount).toBe('COUNT: 0')

      await browser.elementByCss('#self-reload-link').click()

      await retry(async () => {
        expect(await browser.elementByCss('p').text()).toBe('COUNT: 1')
      })
      await browser.close()
    })

    it('should always replace the state', async () => {
      const browser = await next.browser('/nav')

      const countAfterClicked = await browser
        .elementByCss('#self-reload-link')
        .click()
        .waitForElementByCss('#self-reload-page')
        .elementByCss('#self-reload-link')
        .click()
        .elementByCss('#self-reload-link')
        .click()
        .elementByCss('p')
        .text()

      // counts (page change + two clicks)
      expect(countAfterClicked).toBe('COUNT: 3')

      // Since we replace the state, back button would simply go us back to /nav
      await browser.back().waitForElementByCss('.nav-home')

      await browser.close()
    })
  })

  describe('with URL objects', () => {
    it('should work with <Link/>', async () => {
      const browser = await next.browser('/nav')
      const text = await browser
        .elementByCss('#query-string-link')
        .click()
        .waitForElementByCss('.nav-querystring')
        .elementByCss('p')
        .text()
      expect(text).toBe('10')

      expect(await browser.url()).toBe(
        `http://localhost:${next.appPort}/nav/querystring/10#10`
      )
      await browser.close()
    })

    it('should work with "Router.push"', async () => {
      const browser = await next.browser('/nav')
      const text = await browser
        .elementByCss('#query-string-button')
        .click()
        .waitForElementByCss('.nav-querystring')
        .elementByCss('p')
        .text()
      expect(text).toBe('10')

      expect(await browser.url()).toBe(
        `http://localhost:${next.appPort}/nav/querystring/10#10`
      )
      await browser.close()
    })

    it('should work with the "replace" prop', async () => {
      const browser = await next.browser('/nav')

      let stackLength = await browser.eval('window.history.length')

      expect(stackLength).toBe(2)

      // Navigation to /about using a replace link should maintain the url stack length
      const text = await browser
        .elementByCss('#about-replace-link')
        .click()
        .waitForElementByCss('.nav-about')
        .elementByCss('p')
        .text()

      expect(text).toBe('This is the about page.')

      stackLength = await browser.eval('window.history.length')

      expect(stackLength).toBe(2)

      // Going back to the home with a regular link will augment the history count
      await browser
        .elementByCss('#home-link')
        .click()
        .waitForElementByCss('.nav-home')

      stackLength = await browser.eval('window.history.length')

      expect(stackLength).toBe(3)

      await browser.close()
    })

    it('should handle undefined in router.push', async () => {
      const browser = await next.browser('/nav/query-params')
      await browser.elementByCss('#click-me').click()
      const query = JSON.parse(
        await browser.waitForElementByCss('#query-value').text()
      )
      expect(query).toEqual({
        param1: '',
        param2: '',
        param3: '',
        param4: '0',
        param5: 'false',
        param7: '',
        param8: '',
        param9: '',
        param10: '',
        param11: ['', '', '', '0', 'false', '', '', '', '', ''],
      })
    })
  })

  describe('with getInitialProp redirect', () => {
    it('should redirect the page via client side', async () => {
      const browser = await next.browser('/nav')
      const text = await browser
        .elementByCss('#redirect-link')
        .click()
        .waitForElementByCss('.nav-about')
        .elementByCss('p')
        .text()

      expect(text).toBe('This is the about page.')
      await browser.close()
    })

    it('should redirect the page when loading', async () => {
      const browser = await next.browser('/nav/redirect')
      const text = await browser
        .waitForElementByCss('.nav-about')
        .elementByCss('p')
        .text()

      expect(text).toBe('This is the about page.')
      await browser.close()
    })
  })

  describe('with different types of urls', () => {
    it('should work with normal page', async () => {
      const browser = await next.browser('/with-cdm')
      const text = await browser.elementByCss('p').text()

      expect(text).toBe('ComponentDidMount executed on client.')
      await browser.close()
    })

    it('should work with dir/ page', async () => {
      const browser = await next.browser('/nested-cdm')
      const text = await browser.elementByCss('p').text()

      expect(text).toBe('ComponentDidMount executed on client.')
      await browser.close()
    })

    it('should not work with /index page', async () => {
      const browser = await next.browser('/index')
      expect(await browser.elementByCss('h1').text()).toBe('404')
      expect(await browser.elementByCss('h2').text()).toBe(
        'This page could not be found.'
      )
      await browser.close()
    })

    it('should work with / page', async () => {
      const browser = await next.browser('/')
      const text = await browser.elementByCss('p').text()

      expect(text).toBe('ComponentDidMount executed on client.')
      await browser.close()
    })
  })

  describe('with the HOC based router', () => {
    it('should navigate as expected', async () => {
      const browser = await next.browser('/nav/with-hoc')

      const pathname = await browser.elementByCss('#pathname').text()
      expect(pathname).toBe('Current path: /nav/with-hoc')

      const asPath = await browser.elementByCss('#asPath').text()
      expect(asPath).toBe('Current asPath: /nav/with-hoc')

      const text = await browser
        .elementByCss('.nav-with-hoc a')
        .click()
        .waitForElementByCss('.nav-home')
        .elementByCss('p')
        .text()

      expect(text).toBe('This is the home.')
      await browser.close()
    })
  })

  describe('runtime errors', () => {
    it('should show redbox when a client side error is thrown inside a component', async () => {
      const isReact18 = process.env.NEXT_TEST_REACT_VERSION?.startsWith('18')
      const pageErrors: unknown[] = []
      const browser = await next.browser('/error-inside-browser-page', {
        beforePageLoad: (page) => {
          page.on('pageerror', (error: unknown) => {
            pageErrors.push(error)
          })
        },
      })
      await retry(async () => {
        expect(await getRedboxTotalErrorCount(browser)).toBe(isReact18 ? 3 : 1)
      })
      if (isReact18) {
        await expect(browser).toDisplayRedbox(`
         [
           {
             "description": "An Expected error occurred",
             "environmentLabel": null,
             "label": "Runtime Error",
             "source": "pages/error-inside-browser-page.js (5:13) @ ErrorInRenderPage.render
         > 5 |       throw new Error('An Expected error occurred')
             |             ^",
             "stack": [
               "ErrorInRenderPage.render pages/error-inside-browser-page.js (5:13)",
             ],
           },
           {
             "description": "An Expected error occurred",
             "environmentLabel": null,
             "label": "Runtime Error",
             "source": "pages/error-inside-browser-page.js (5:13) @ ErrorInRenderPage.render
         > 5 |       throw new Error('An Expected error occurred')
             |             ^",
             "stack": [
               "ErrorInRenderPage.render pages/error-inside-browser-page.js (5:13)",
             ],
           },
           {
             "description": "There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.",
             "environmentLabel": null,
             "label": "Recoverable Error",
             "source": null,
             "stack": [],
           },
         ]
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "An Expected error occurred",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": "pages/error-inside-browser-page.js (5:13) @ ErrorInRenderPage.render
         > 5 |       throw new Error('An Expected error occurred')
             |             ^",
           "stack": [
             "ErrorInRenderPage.render pages/error-inside-browser-page.js (5:13)",
           ],
         }
        `)
      }
      expect(pageErrors).toEqual(
        isReact18
          ? [
              expect.objectContaining({
                message: 'An Expected error occurred',
              }),
              expect.objectContaining({
                message: 'An Expected error occurred',
              }),
              expect.objectContaining({
                message:
                  'There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.',
              }),
            ]
          : // TODO(veil): Should contain thrown error
            []
      )
    })

    it('should show redbox when a client side error is thrown outside a component', async () => {
      const pageErrors: unknown[] = []
      const browser = await next.browser('/error-in-the-browser-global-scope', {
        beforePageLoad: (page) => {
          page.on('pageerror', (error: unknown) => {
            pageErrors.push(error)
          })
        },
      })

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
           {
             "description": "An Expected error occurred",
             "environmentLabel": null,
             "label": "Runtime Error",
             "source": "pages/error-in-the-browser-global-scope.js (2:9) @ [project]/pages/error-in-the-browser-global-scope.js [client] (ecmascript)
           > 2 |   throw new Error('An Expected error occurred')
               |         ^",
             "stack": [
               "[project]/pages/error-in-the-browser-global-scope.js [client] (ecmascript) pages/error-in-the-browser-global-scope.js (2:9)",
             ],
           }
          `)
      } else {
        await expect(browser).toDisplayRedbox(`
           {
             "description": "An Expected error occurred",
             "environmentLabel": null,
             "label": "Runtime Error",
             "source": "pages/error-in-the-browser-global-scope.js (2:9) @ eval
           > 2 |   throw new Error('An Expected error occurred')
               |         ^",
             "stack": [
               "eval pages/error-in-the-browser-global-scope.js (2:9)",
               "<FIXME-next-dist-dir>",
             ],
           }
          `)
      }
      expect(pageErrors).toEqual([
        expect.objectContaining({ message: 'An Expected error occurred' }),
      ])
    })
  })

  it('should not error on module.exports + polyfills', async () => {
    const browser = await next.browser('/read-only-object-error')
    expect(await browser.elementByCss('body').text()).toBe(
      'this is just a placeholder component'
    )
  })

  it('should work on nested /index/index.js', async () => {
    const browser = await next.browser('/nested-index/index')
    expect(await browser.elementByCss('p').text()).toBe(
      'This is an index.js nested in an index/ folder.'
    )
    await browser.close()
  })

  it('should handle undefined prop in head client-side', async () => {
    const browser = await next.browser('/head')
    const value = await browser.eval(
      `document.querySelector('meta[name="empty-content"]').hasAttribute('content')`
    )

    expect(value).toBe(false)
  })

  it.each([true, false])(
    'should handle boolean async prop in next/script client-side: %s',
    async (bool) => {
      const browser = await next.browser('/script')
      const value = await browser.eval(
        `document.querySelector('script[src="/test-async-${JSON.stringify(
          bool
        )}.js"]').async`
      )

      expect(value).toBe(bool)
    }
  )

  it('should only execute async and defer scripts with next/script once', async () => {
    const browser = await next.browser('/script')

    await browser.waitForElementByCss('h1')
    await waitFor(2000)
    expect(Number(await browser.eval('window.__test_async_executions'))).toBe(1)
    expect(Number(await browser.eval('window.__test_defer_executions'))).toBe(1)
  })

  it('should emit routeChangeError on hash change cancel', async () => {
    const browser = await next.browser('/')

    await browser.eval(`(function() {
      window.routeErrors = []

      window.next.router.events.on('routeChangeError', function (err) {
        window.routeErrors.push(err)
      })
      window.next.router.push('#first')
      window.next.router.push('#second')
      window.next.router.push('#third')
    })()`)

    await check(async () => {
      const errorCount = await browser.eval('window.routeErrors.length')
      return errorCount > 0 ? 'success' : errorCount
    }, 'success')
  })

  it('should navigate to paths relative to the current page', async () => {
    const browser = await next.browser('/nav/relative')
    let page

    await browser.elementByCss('a').click()

    await browser.waitForElementByCss('#relative-1')
    page = await browser.elementByCss('body').text()
    expect(page).toMatch(/On relative 1/)
    await browser.elementByCss('a').click()

    await browser.waitForElementByCss('#relative-2')
    page = await browser.elementByCss('body').text()
    expect(page).toMatch(/On relative 2/)

    await browser.elementByCss('button').click()
    await browser.waitForElementByCss('#relative')
    page = await browser.elementByCss('body').text()
    expect(page).toMatch(/On relative index/)

    await browser.close()
  })
})