Mock `router` to test component using Jest
See original GitHub issueIssue Description
I want to test my components with Snapshots and am using Jest to do so. Since my component is using withRoute HOC, both my component and somewher in HOC require router
and all its functions in their in the contexts.
Is there a easy way to create an instance of router
or mock it?
Here is a sample of my code:
const initialState = store.getState();
const router = {}; // ???
test('Login changes', () => {
const wrapper = shallow(<Login />, {
context: { store: mockStore(initialState), router }
});
expect(wrapper.dive()).toMatchSnapshot();
});
Issue Analytics
- State:
- Created 5 years ago
- Reactions:2
- Comments:24 (11 by maintainers)
Top Results From Across the Web
Mock Router in React testing library and jest - Stack Overflow
Assuming you use react-router, You can use the Memory router for the testing which is easier and performant. I might have typos or...
Read more >Testing React Router with Jest - In Plain English
Firstly, we need to mock the modules of all the components the Router routes to. The modules that contain the components need to...
Read more >How to mock Next router with Jest - DEV Community
To demonstrate how to mock next/router I will use an example. The example files and tests are available on github and are build...
Read more >React Router - Testing Library
In your tests, pass the history object as a whole to the Router component. Note: React Router v5 only works with History v4,...
Read more >Mocking React Router's match object in component unit tests
When testing these components with Testing Library / Jest, we need a way to mock routes and route parameter values via React Router's...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Any update on this?
I was able to mock ‘found’ module by doing jest.mock(‘found’), but couldn’t the router itself.
Following @taion comment the test passed (although it seems to me like a temporary solution) by defining router as: