我具有呈现应用程序路由的以下组件:https://jsbin.com/bahaxudijo/edit?js,我正在尝试模拟BrowserRouter和Route来进行测试,这是我的测试:
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();
});
});
});
但是我嘲笑错误的BrowserRouter和Route,所以测试通过了,但是快照只是空的div。如何正确模拟BrowserRouter和路由?
答案 0 :(得分:6)
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(),
};
});
答案 1 :(得分:1)
另一种方式:
const rrd = require('react-router-dom');
jest.spyOn(rrd, 'BrowserRouter').mockImplementation(({children}) => children);
来源:
答案 2 :(得分:0)
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;