score:41
you actually do not need to mock react-router-dom
(at least for v5) as it provides a bunch of testing tools: https://v5.reactrouter.com/web/guides/testing
to check your history is actually changed, you can use creatememoryhistory
and inspect its content:
import react from 'react';
import { render, screen } from '@testing-library/react';
import userevent from '@testing-library/user-event';
import { menu } from './menu';
import { creatememoryhistory } from 'history'
import { router } from 'react-router-dom';
test('triggers path change', () => {
const history = creatememoryhistory();
render(
<router history={history}>
<menu />
</router>
);
const aboutitem = screen.getbytext('about');
expect(aboutitem).tobeinthedocument();
userevent.click(aboutitem);
expect(history.length).tobe(2);
expect(history.location.pathname).tobe('/about');
});
score:-2
this may be helpful. you can use jest.fn() to mock history.push().
const historymock = { push: jest.fn() }
expect(historymock.push.mock.calls[0]).toequal([
{
pathname: "/profile", // url
search: , // search-data
},
]);
score:95
use jest.mock
in module scope will automatically be hoisted to the top of the code block. so that you can get the mocked version react-router-dom
in notfound.jsx
file and your test file.
besides, we only want to mock usehistory
hook, so we should use jest.requireactual()
to get the original module and keep other methods as the original version.
here is the solution:
notfound.jsx
:
import react from 'react';
import { usehistory } from 'react-router-dom';
const routenotfound = () => {
const history = usehistory();
return (
<div>
<button onclick={() => history.push('/help')} />
</div>
);
};
export default routenotfound;
notfound.test.jsx
:
import react from 'react';
import { memoryrouter } from 'react-router-dom';
import { render, fireevent } from '@testing-library/react';
import routenotfound from './notfound';
const mockhistorypush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireactual('react-router-dom'),
usehistory: () => ({
push: mockhistorypush,
}),
}));
describe('routenotfound', () => {
it('redirects to correct url on click', () => {
const { getbyrole } = render(
<memoryrouter>
<routenotfound />
</memoryrouter>,
);
fireevent.click(getbyrole('button'));
expect(mockhistorypush).tohavebeencalledwith('/help');
});
});
unit test result with 100% coverage:
pass src/stackoverflow/58524183/notfound.test.jsx
routenotfound
✓ redirects to correct url on click (66ms)
--------------|----------|----------|----------|----------|-------------------|
file | % stmts | % branch | % funcs | % lines | uncovered line #s |
--------------|----------|----------|----------|----------|-------------------|
all files | 100 | 100 | 100 | 100 | |
notfound.jsx | 100 | 100 | 100 | 100 | |
--------------|----------|----------|----------|----------|-------------------|
test suites: 1 passed, 1 total
tests: 1 passed, 1 total
snapshots: 0 total
time: 5.133s, estimated 11s
source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58524183
Source: stackoverflow.com
Related Query
- How to mock history.push with the new React Router Hooks using Jest
- React how to pass the id to router using history push
- How to fetch the new data in response to React Router change with Redux?
- How to structure a component using React Hooks with an object that uses the DOM directly? (such as OpenLayers)?)
- How to mock properly with Jest a React component using render props
- How to push a new value into the current array using the react hooks?
- How can I make react render the new state modifications after I have updated the state with hooks and context
- How can I access the history instance outside of React app with React Router v4?
- React Router -- history push state not refreshing with new state object
- With React Router v4, how to navigate to a path based upon the existing browser location but with new params interpolated?
- How to click a button and navigate to a new route with URL params using React Router 4
- How can I mock with jest multiple different responses when I'm using custom react hooks?
- Im using React Router and I want one of my route links with path="/" to be the home page on reload.. How can you do that?
- How to pass down functions as a prop with the new React Hooks
- How to manipulate the DOM inside of map function using onChange event on one of the checkboxes with react hooks
- How to navgiate to a new page using react router dom with typescript
- Is using the destructured state to calculate new state with react hooks safe?
- How do I test a polling react hook using Jest with mock timers?
- How to push to History in React Router v4?
- How to test a className with the Jest and React testing library
- How to mock React component methods with jest and enzyme
- Testing React Functional Component with Hooks using Jest
- Using Jest to mock a React component with props
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How do I use the Firebase onAuthStateChange with the new React Hooks?
- How to mock out sub-components when unit testing a React component with Jest
- How should the new context api work with React Native navigator?
- React Hooks with React Router v4 - how do I redirect to another route?
- mock useDispatch in jest and test the params with using that dispatch action in functional component
- how to access history object in new React Router v4
More Query from same tag
- How to get Image name while updating in react js?
- can not assign new property in react , got ` can't add property yyy, object is not extensible`
- React Hook Form Error - Type 'UseFormRegister<FormData>' is not assignable to type 'LegacyRef<HTMLInputElement> | undefined'
- How to create a sidebar with react-router and style the buttons
- How to toggle state between 2 React components
- drop-down resetting does not visible in UI although the state value is reset ReactJs
- Telegram Web Bots data validation in JavaScript
- MUI v5 @mui/material/styles vs @emotion/react
- React JS doesn't render after function is done
- ReactJS: I can not get the state to update with API data when the asynchronous API data fetch is completed
- React Admin: I'd like to route to <Show> view from a list
- React's props with the same name as their value
- How can I maintain state and "this" with react component functions
- Conditionally render elements in React JS?
- How to avoid the Reactjs (Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.). from below component
- How to add a row to the beginning of a table with react
- React Native & Android?
- React : Toggling PopUp re-renders entire component
- using browserify-css in gulp
- React result from input onChange
- How to add a className to single .map item?
- onClick function for array of buttons not working
- React SignalR - Do not send bearer token in URL
- How can I Update Document in Collection firebase
- Iterating through nested object in Reactjs?
- Getting an error during the dependency installation of Strapi installation process
- Can we map over two arrays at same time in js?
- React: duplicate values only display on first item in material ui table
- Can I guarantee the render order of an array of React components?
- Loading bar with percentage in React