How to mock useRouter from next/router in Cypress component testing? #22715
Replies: 6 comments 7 replies
-
Got rid of this error this way. Next 12. Router won't work as expected(pushes won't work, but you can test what was pushed to router). |
Beta Was this translation helpful? Give feedback.
-
Updated for Next 13.5.6 and Cypress 13.3.1. I created a utility function in
In any test where I want to mock the router, I simply
|
Beta Was this translation helpful? Give feedback.
-
Not sure what version of Next changed this, but on import {
AppRouterContext,
AppRouterInstance,
} from 'next/dist/shared/lib/app-router-context'
const createRouter = (params: Partial<AppRouterInstance>) => ({
back: cy.spy().as('back'),
forward: cy.spy().as('forward'),
prefetch: cy.stub().as('prefetch').resolves(),
push: cy.spy().as('push'),
replace: cy.spy().as('replace'),
refresh: cy.spy().as('refresh'),
...params,
})
interface MockNextRouterProps extends Partial<AppRouterInstance> {
children: React.ReactNode
}
const MockNextRouter = ({ children, ...props }: MockNextRouterProps) => {
const router = createRouter(props as AppRouterInstance)
return (
<AppRouterContext.Provider value={router}>
{children}
</AppRouterContext.Provider>
)
}
export default MockNextRouter |
Beta Was this translation helpful? Give feedback.
-
Is there something similar to memoryrouter for next? |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
I use this package https://www.npmjs.com/package/next-router-mock Use it as
|
Beta Was this translation helpful? Give feedback.
-
Hey community,
I use Cypress for components testing in my project.
Here is the code snippet from my component:
and this is how I want to test it:
For now, I've got this error:
How can I mock
useRouter
, or perhaps you can suggest another way to manage this test to be successfully running?Thanks a lot in advance!
Beta Was this translation helpful? Give feedback.
All reactions