Skip to content

Instantly share code, notes, and snippets.

@novascreen
Last active November 18, 2021 08:11
Show Gist options
  • Save novascreen/f1c44ead31e5a494556793be2c408840 to your computer and use it in GitHub Desktop.
Save novascreen/f1c44ead31e5a494556793be2c408840 to your computer and use it in GitHub Desktop.
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:

vercel/next.js#1827

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

Patrick-DS commented Jul 25, 2021

When I do this and I click a link on a story, I get a blank page with the text Cannot GET /some/example/[endpoint]/here. Do you know why this happens? I'm using NextJS version 10.2.3 and Storybook version 5.1.10. In other words, prefetching works fine (I can even put a storybook action in the function call before returning the promise as above and I see the action in Storybook when hovering on a link, which fires the prefetch method). But pushing is another story.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment