next.js: jest example fails with `next/link`

Example repo: https://github.com/remy/next-examples/tree/master/with-jest#fails-with

The jest example in the examples directory is too simple, so it quickly falls over when I started testing a slightly larger app (than a single page with some jsx).

How do we get snapshot testing to work with next? Can we have jest tell next (somehow???) that prefetch shouldn’t happen?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 1
  • Comments: 23 (7 by maintainers)

Commits related to this issue

Most upvoted comments

@kgoggin it seems that I understood. for anybody using prefetch:

import Router from 'next/router'
const mockedRouter = { push: () => {}, prefetch: () => {} }
Router.router = mockedRouter

Yes. When we use next/router or next/link with prefetch, it’ll fail inside JEST. That’s because there’s no actual router instance.

We need to find a way to mock this. Something like this would work. Haven’t tested.

import Router from `next/router`
const mockedRouter = { push: () => {} }
Router.router = mockedRouter

in the end for storybook (not for jest) I mocked it like this in config:

const actionWithPromise = () => {
  action('clicked link')();
  // we need to return promise because it is needed by Link.linkClicked
  return new Promise((resolve, reject) => reject());
};

const mockedRouter = {
  push: actionWithPromise,
  replace: actionWithPromise,
  prefetch: () => {},
};

Router.router = mockedRouter;

for jest I just have router fully ignored: jest.mock('next/router'); though it may be not enough if Link onClick needs to be simulated

I think we need to fix this bug. On it.

Would be good to see this fixed after almost 2 years. This is a barrier to anyone coming to Next.js as they’ll bump into this pretty soon when they try to mount a component with <Link prefetch> - which you guys recommend.

@kylemh I ran into this and was able to get it working by wrapping the story in a HOC that provides a custom router object in it’s context. It looks like next/router relies on the legacy context API so this will probably break in later versions. Here’s my mock files:

const { Component } = require('react');
const Router = require('next/router').default;
const { action } = require('@storybook/addon-actions');
const PropTypes = require('prop-types');

const actionWithPromise = () => {
  action('clicked link')();
  return new Promise((resolve, reject) => reject());
};

const mockedRouter = {
  push: actionWithPromise,
  replace: actionWithPromise,
  prefetch: () => {},
  route: '/mock-route',
  pathname: 'mock-path',
};

Router.router = mockedRouter;

const withMockRouterContext = (mockRouter) => {
  class MockRouterContext extends Component {
    getChildContext() {
      return {
        router: Object.assign(mockedRouter, mockRouter),
      };
    }
    render() {
      return this.props.children;
    }
  }

  MockRouterContext.childContextTypes = {
    router: PropTypes.object,
  };

  return MockRouterContext;
};

module.exports.mockedRouter = mockedRouter;
module.exports.withMockRouterContext = withMockRouterContext;

Then just wrap your story with a MockRouter:

import { withMockRouterContext } from 'test-utils/react/nextjs/router';

const MockRouter1 = withMockRouterContext([extendDefaultMockRouter]);

stories.add(
  'Default',
  () => (
    <MockRouter1>
      <ActiveLink href="test-active">Test</ActiveLink>
    </MockRouter1>
  )
);

Anybody got advice on mocking withRouter within Storybook and Jest?

I tried withRouter = Component => props => <Component {...props} router={mockedRouter} /> with no success.

For anyone else landing here trying to make this work with a <Link prefetch/> in storybook, I used @arunoda’s example but had to add a prefetch noop on the mocked router as well.

Not sure if this is related, but I’m getting the same error if I’ll try to test container that uses Router.push() function directly. I haven’t really found a way to mock it.