Unverified Commit 55afe80c authored by Damien Varron's avatar Damien Varron Committed by GitHub

Only prefetch Link if router is in context (#19857)

Fixes #16864 

The `router` can be missing in a test environment when trying to render a `Link` component. This PR bails out of `router.prefetch()` when `router` is missing.

The alternative is for users to mock `next/link` or to mock the `router` and wrap their test components.

Please let me know any feedback.
parent ccf26a85
......@@ -41,7 +41,7 @@ function prefetch(
as: string,
options?: PrefetchOptions
): void {
if (typeof window === 'undefined') return
if (typeof window === 'undefined' || !router) return
if (!isLocalURL(href)) return
// Prefetch the JSON page if asked (only in the client)
// We need to handle a prefetch error here since we may be
......
import React from 'react'
import Link from 'next/link'
export default function Hello() {
return (
<Link href="/">
<a>Click me</a>
</Link>
)
}
/**
* @jest-environment jsdom
*/
import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import { act } from 'react-dom/test-utils'
import Hello from '../components/hello'
describe('Link without a router', () => {
let container = null
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
})
afterEach(() => {
unmountComponentAtNode(container)
container.remove()
container = null
})
describe('dev mode', () => {
it('should not throw when rendered', () => {
jest.useFakeTimers()
act(() => {
render(<Hello />, container)
})
act(() => {
jest.runAllTimers()
})
expect(container.textContent).toBe('Click me')
})
})
describe('production mode', () => {
it('should not throw when rendered', () => {
jest.useFakeTimers()
act(() => {
render(<Hello />, container)
})
act(() => {
jest.runAllTimers()
})
expect(container.textContent).toBe('Click me')
})
})
})
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