Skip to content

Commit

Permalink
Make sure to handle rejection when prefetching pages
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk committed Feb 18, 2020
1 parent c66f2f7 commit f9f0a99
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/next/client/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,10 @@ class Link extends Component<LinkProps> {
if (!this.p || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client)
const [href, asPath] = this.getPaths()
Router.prefetch(href, asPath, options)
// make sure to catch here since we should have an unhandledRejection
// since we're doing this automatically and we don't want to reload the
// page while automatically prefetching for the user
Router.prefetch(href, asPath, options).catch(() => {})
prefetched[href] = true
}

Expand Down
9 changes: 9 additions & 0 deletions test/integration/preload-viewport/pages/invalid-prefetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Link from 'next/link'

export default () => (
<>
<Link href="/something-invalid-oops">
<a id="invalid-link">I'm broken...</a>
</Link>
</>
)
15 changes: 15 additions & 0 deletions test/integration/preload-viewport/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,21 @@ describe('Prefetching Links in viewport', () => {
}
})

it('should not have unhandledRejection when failing to prefetch on link', async () => {
const browser = await webdriver(appPort, '/')
await browser.eval(`(function() {
window.addEventListener('unhandledrejection', function (err) {
window.hadUnhandledReject = true;
})
window.next.router.push('/invalid-prefetch');
})()`)

expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()

await browser.elementByCss('#invalid-link').moveTo()
expect(await browser.eval('window.hadUnhandledReject')).toBeFalsy()
})

it('should not prefetch when prefetch is explicitly set to false', async () => {
const browser = await webdriver(appPort, '/opt-out')

Expand Down

0 comments on commit f9f0a99

Please sign in to comment.