Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to mock next/router in Storybook

If you use Storybook with Next.js and have components using next/link you'll have to mock next/router the same you would for testing with Jest or others. Simply create a file with the mock router as shown below and import it in your Storybook config.

This is based on some information from an issue on Next.js:

https://github.com/zeit/next.js/issues/1827

import { configure } from '@storybook/react';
import './mockNextRouter';
/* ... */
import Router from 'next/router';
Router.router = {
push: () => {},
prefetch: () => {},
};
@noe-lc

This comment has been minimized.

Copy link

@noe-lc noe-lc commented May 19, 2020

For people working with Next 9.4.0 or higher, make the prefetch function return a promise

Router.router = {
    push: () => {},
    prefetch: () => new Promise((resolve, reject) => {}),
};

to prevent the following error:
link.js:14 Uncaught TypeError: Cannot read property 'catch' of undefined at Link.prefetch (link.js:14)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.