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
- test commit toc check following error : You should only use "next/router" inside the client side of your app. https://github.com/zeit/next.js/issues/1827 — committed to sumitparakh/front-end by sumitparakh 8 years ago
- Don’t prefetch outside of production (#6578) Fixes #1827 This doesn't affect integration tests as they'd use `next build` which forces production mode. Development forces `development`. — committed to vercel/next.js by timneutkens 8 years ago
@kgoggin it seems that I understood. for anybody using prefetch:
Yes. When we use
next/routerornext/linkwith 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.
in the end for storybook (not for jest) I mocked it like this in config:
for jest I just have router fully ignored:
jest.mock('next/router');though it may be not enough if Link onClick needs to be simulatedI 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
mounta 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:
Then just wrap your story with a MockRouter:
Anybody got advice on mocking
withRouterwithin 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 aprefetchnoop 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.