Unverified Commit fe2d26fc authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add unit test for navigateReducer and refreshReducer (#45486)



Adds additional unit tests.

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 308d1834
...@@ -58,7 +58,7 @@ const HotReloader: ...@@ -58,7 +58,7 @@ const HotReloader:
const prefetched = new Set<string>() const prefetched = new Set<string>()
type AppRouterProps = Omit< type AppRouterProps = Omit<
InitialRouterStateParameters, Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes' 'initialParallelRoutes'
> & { > & {
initialHead: ReactNode initialHead: ReactNode
...@@ -97,9 +97,11 @@ function findHeadInCache( ...@@ -97,9 +97,11 @@ function findHeadInCache(
} }
function isExternalURL(url: URL) { function isExternalURL(url: URL) {
return url.origin !== location.origin return url.origin !== window.location.origin
} }
const isServer = typeof window === 'undefined'
/** /**
* The global router that wraps the application components. * The global router that wraps the application components.
*/ */
...@@ -117,6 +119,8 @@ function Router({ ...@@ -117,6 +119,8 @@ function Router({
initialCanonicalUrl, initialCanonicalUrl,
initialTree, initialTree,
initialParallelRoutes, initialParallelRoutes,
isServer,
location: !isServer ? window.location : null,
}), }),
[children, initialCanonicalUrl, initialTree] [children, initialCanonicalUrl, initialTree]
) )
...@@ -261,6 +265,7 @@ function Router({ ...@@ -261,6 +265,7 @@ function Router({
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: {}, mutable: {},
origin: window.location.origin,
}) })
}) })
}, },
......
...@@ -10,6 +10,8 @@ export interface InitialRouterStateParameters { ...@@ -10,6 +10,8 @@ export interface InitialRouterStateParameters {
initialCanonicalUrl: string initialCanonicalUrl: string
children: ReactNode children: ReactNode
initialParallelRoutes: CacheNode['parallelRoutes'] initialParallelRoutes: CacheNode['parallelRoutes']
isServer: boolean
location: Location | null
} }
export function createInitialRouterState({ export function createInitialRouterState({
...@@ -17,6 +19,8 @@ export function createInitialRouterState({ ...@@ -17,6 +19,8 @@ export function createInitialRouterState({
children, children,
initialCanonicalUrl, initialCanonicalUrl,
initialParallelRoutes, initialParallelRoutes,
isServer,
location,
}: InitialRouterStateParameters) { }: InitialRouterStateParameters) {
return { return {
tree: initialTree, tree: initialTree,
...@@ -24,8 +28,7 @@ export function createInitialRouterState({ ...@@ -24,8 +28,7 @@ export function createInitialRouterState({
status: CacheStates.READY, status: CacheStates.READY,
data: null, data: null,
subTreeData: children, subTreeData: children,
parallelRoutes: parallelRoutes: isServer ? new Map() : initialParallelRoutes,
typeof window === 'undefined' ? new Map() : initialParallelRoutes,
} as CacheNode, } as CacheNode,
prefetchCache: new Map(), prefetchCache: new Map(),
pushRef: { pendingPush: false, mpaNavigation: false }, pushRef: { pendingPush: false, mpaNavigation: false },
...@@ -33,9 +36,9 @@ export function createInitialRouterState({ ...@@ -33,9 +36,9 @@ export function createInitialRouterState({
canonicalUrl: canonicalUrl:
// location.href is read as the initial value for canonicalUrl in the browser // location.href is read as the initial value for canonicalUrl in the browser
// This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file. // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.
typeof window !== 'undefined' location
? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs. ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.
createHrefFromUrl(window.location) createHrefFromUrl(location)
: initialCanonicalUrl, : initialCanonicalUrl,
} }
} }
import React from 'react'
import type { fetchServerResponse } from '../fetch-server-response'
import type { FlightData } from '../../../../server/app-render'
jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [
[
'children',
'linking',
'children',
'about',
[
'about',
{
children: ['', {}],
},
],
<h1>About Page!</h1>,
<>
<title>About page!</title>
</>,
],
]
return {
fetchServerResponse: (url: URL): ReturnType<typeof fetchServerResponse> => {
if (url.pathname === '/linking/about') {
return Promise.resolve([flightData, undefined])
}
throw new Error('unknown url in mock')
},
}
})
import { FlightRouterState } from '../../../../server/app-render'
import {
CacheNode,
CacheStates,
} from '../../../../shared/lib/app-router-context'
import { createInitialRouterState } from '../create-initial-router-state'
import { NavigateAction, ACTION_NAVIGATE } from '../router-reducer-types'
import { navigateReducer } from './navigate-reducer'
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
]
async function runPromiseThrowChain(fn: any): Promise<any> {
try {
return await fn()
} catch (err) {
if (err instanceof Promise) {
await err
return await runPromiseThrowChain(fn)
}
throw err
}
}
describe('navigateReducer', () => {
it('should apply navigation', async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
])
const state = createInitialRouterState({
initialTree,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
const action: NavigateAction = {
type: ACTION_NAVIGATE,
url: new URL('/linking/about', 'https://localhost'),
isExternalUrl: false,
navigateType: 'push',
forceOptimisticNavigation: false,
cache: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: {},
}
const newState = await runPromiseThrowChain(() =>
navigateReducer(state, action)
)
const expectedState: ReturnType<typeof navigateReducer> = {
prefetchCache: new Map(),
pushRef: {
mpaNavigation: false,
pendingPush: true,
},
focusAndScrollRef: {
apply: true,
},
canonicalUrl: '/linking/about',
cache: {
status: CacheStates.READY,
data: null,
subTreeData: (
<html>
<head></head>
<body>Root layout</body>
</html>
),
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
[
'about',
{
status: CacheStates.READY,
data: null,
subTreeData: <h1>About Page!</h1>,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.LAZY_INITIALIZED,
data: null,
head: (
<>
<title>About page!</title>
</>
),
parallelRoutes: new Map(),
subTreeData: null,
},
],
]),
],
]),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
]),
},
tree: [
'',
{
children: [
'linking',
{
children: ['about', { children: ['', {}] }],
},
],
},
undefined,
undefined,
true,
],
}
expect(newState).toMatchObject(expectedState)
})
})
import React from 'react'
import type { fetchServerResponse } from '../fetch-server-response'
import type { FlightData } from '../../../../server/app-render'
jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [
[
[
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
null,
null,
true,
],
<html>
<head></head>
<body>
<h1>Linking Page!</h1>
</body>
</html>,
<>
<title>Linking page!</title>
</>,
],
]
return {
fetchServerResponse: (url: URL): ReturnType<typeof fetchServerResponse> => {
if (url.pathname === '/linking') {
return Promise.resolve([flightData, undefined])
}
throw new Error('unknown url in mock')
},
}
})
import { FlightRouterState } from '../../../../server/app-render'
import {
CacheNode,
CacheStates,
} from '../../../../shared/lib/app-router-context'
import { createInitialRouterState } from '../create-initial-router-state'
import { RefreshAction, ACTION_REFRESH } from '../router-reducer-types'
import { refreshReducer } from './refresh-reducer'
const getInitialRouterStateTree = (): FlightRouterState => [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
undefined,
undefined,
true,
]
async function runPromiseThrowChain(fn: any): Promise<any> {
try {
return await fn()
} catch (err) {
if (err instanceof Promise) {
await err
return await runPromiseThrowChain(fn)
}
throw err
}
}
describe('refreshReducer', () => {
it('should apply refresh', async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
])
const state = createInitialRouterState({
initialTree,
initialCanonicalUrl,
children,
initialParallelRoutes,
isServer: false,
location: new URL('/linking', 'https://localhost') as any,
})
const action: RefreshAction = {
type: ACTION_REFRESH,
cache: {
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
const newState = await runPromiseThrowChain(() =>
refreshReducer(state, action)
)
const expectedState: ReturnType<typeof refreshReducer> = {
prefetchCache: new Map(),
pushRef: {
mpaNavigation: false,
pendingPush: false,
},
focusAndScrollRef: {
apply: false,
},
canonicalUrl: '/linking',
cache: {
status: CacheStates.READY,
data: null,
subTreeData: (
<html>
<head></head>
<body>
<h1>Linking Page!</h1>
</body>
</html>
),
parallelRoutes: new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.LAZY_INITIALIZED,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
parallelRoutes: new Map(),
head: (
<>
<title>Linking page!</title>
</>
),
},
],
]),
],
]),
data: null,
subTreeData: null,
},
],
]),
],
]),
},
tree: [
'',
{
children: [
'linking',
{
children: ['', {}],
},
],
},
null,
null,
true,
],
}
expect(newState).toMatchObject(expectedState)
})
})
...@@ -16,7 +16,7 @@ export function refreshReducer( ...@@ -16,7 +16,7 @@ export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: RefreshAction action: RefreshAction
): ReducerState { ): ReducerState {
const { cache, mutable } = action const { cache, mutable, origin } = action
const href = state.canonicalUrl const href = state.canonicalUrl
const isForCurrentTree = const isForCurrentTree =
...@@ -62,9 +62,10 @@ export function refreshReducer( ...@@ -62,9 +62,10 @@ export function refreshReducer(
} }
if (!cache.data) { if (!cache.data) {
// TODO-APP: verify that `href` is not an external url.
// Fetch data from the root of the tree. // Fetch data from the root of the tree.
cache.data = createRecordFromThenable( cache.data = createRecordFromThenable(
fetchServerResponse(new URL(href, location.origin), [ fetchServerResponse(new URL(href, origin), [
state.tree[0], state.tree[0],
state.tree[1], state.tree[1],
state.tree[2], state.tree[2],
......
...@@ -25,6 +25,7 @@ export interface RefreshAction { ...@@ -25,6 +25,7 @@ export interface RefreshAction {
type: typeof ACTION_REFRESH type: typeof ACTION_REFRESH
cache: CacheNode cache: CacheNode
mutable: Mutable mutable: Mutable
origin: Location['origin']
} }
/** /**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment