I have this components that renders the routes of an app: https://jsbin.com/bahaxudijo/edit?js, I'm trying to mock the BrowserRouter and the Route to do the test, this are my test:
import React from 'react';
import renderer from 'react-test-renderer';
import Router from '../../../components/Router/Component';
jest.mock('react-router-dom', () => ({
BrowserRouter: ({ children }) => <div>{children}</div>,
Route: ({ children }) => <div>{children}</div>,
}));
jest.mock('../../../components/Nav/index', () => '<MockedNav />');
jest.mock('../../../components/ScheduleManager/index', () => '<MockedScheduleManager />');
const props = {
token: '',
loginStaff: jest.fn(),
};
describe('<Router />', () => {
describe('When is passed a token', () => {
it('renders the correct route', () => {
const component = renderer.create(<Router {...props} />);
expect(component).toMatchSnapshot();
});
});
});
But I'm mocking wrong the BrowserRouter and the Route, so the test passes but the snapshots are only empty divs. How can I properly mock the BrowserRouter and the Route?
jest.mock('react-router-dom', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('react-router-dom');
return {
__esModule: true,
...originalModule,
// add your noops here
useParams: jest.fn(),
useHistory: jest.fn(),
};
});
Yet another way:
const rrd = require('react-router-dom');
jest.spyOn(rrd, 'BrowserRouter').mockImplementation(({children}) => children);
Sources:
const reactRouter = require('react-router-dom');
const { MemoryRouter } = reactRouter;
const MockBrowserRouter = ({ children }) => (
<MemoryRouter initialEntries={['/']}>
{ children }
</MemoryRouter>
);
MockBrowserRouter.propTypes = { children: PropTypes.node.isRequired };
reactRouter.BrowserRouter = MockBrowserRouter;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With