Mock next/navigation #53499
Replies: 6 comments 5 replies
-
|
Beta Was this translation helpful? Give feedback.
-
Thank you sooooo much ❤️ This solved my problem I made one addition with /** New next/navigation mock */
jest.mock('next/navigation', () => {
return {
__esModule: true,
usePathname: () => ({
pathname: '',
}),
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn(),
}),
useSearchParams: () => ({
get: () => {}
})
}
}) |
Beta Was this translation helpful? Give feedback.
-
Adding on to this in case it helps anyone, I also had to mock useServerInsertedHTML jest.mock('next/navigation', () => {
return {
__esModule: true,
usePathname: () => ({ pathname: '' }),
useRouter: () => ({
push: jest.fn(),
replace: jest.fn(),
prefetch: jest.fn()
}),
useSearchParams: () => ({ get: () => {} }),
useServerInsertedHTML: jest.fn()
};
}); |
Beta Was this translation helpful? Give feedback.
-
I'm using Map for useSearchParams to mock the API more accurate in case you use like
|
Beta Was this translation helpful? Give feedback.
-
Did anyone have any luck mocking this in cypress? cy.stub doesn’t do anything to next/navigation 😡 |
Beta Was this translation helpful? Give feedback.
-
Here is what I tried and what worked for me: const mockRouterReplace = jest.fn();
const mockRouterRefresh = jest.fn();
const mockRouterPush = jest.fn();
jest.mock('next/navigation', () => {
const originalModule = jest.requireActual('next/navigation');
return {
__esModule: true,
...originalModule,
useRouter: jest.fn().mockImplementation(() => {
return {
push: mockRouterPush,
replace: mockRouterReplace,
refresh: mockRouterRefresh
};
}),
useSearchParams: jest.fn().mockImplementation(() => {
return new URLSearchParams(window.location.search);
}),
usePathname: jest.fn().mockImplementation((pathArg) => {
return pathArg;
})
};
}); Then in your tests you can use it like so: afterEach(() => {
mockRouterRefresh.mockRestore();
mockRouterReplace.mockRestore();
mockRouterPush.mockRestore();
});
it('calls the router push method', async() => {
expect(mockRouterPush).toHaveBeenCalledTimes(1);
expect(mockRouterPush).toHaveBeenCalledWith('/'); // Route Push argument
});
it('calls the router replace method', async() => {
expect(mockRouterReplace).toHaveBeenCalledTimes(1);
expect(mockRouterReplace).toHaveBeenCalledWith('/home'); // Route Replace argument
});
it('calls the router push method', async() => {
expect(mockRouterReset).toHaveBeenCalledTimes(1);
}); |
Beta Was this translation helpful? Give feedback.
-
Summary
`const useRouter = jest.spyOn(require('next/router'), 'useRouter') let push: jest.Mock<any, any>
beforeEach(() => {
push = jest.fn()
useRouter.mockReturnValue({
query: {},
push: push
})
})
` before the update it used like this now it doesn't work anymore as it would in nextjs13? using next/navigation
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions