如何使用笑话模拟 react-router-dom 的 BrowserRouter



我有以下组件来呈现应用程序的路由: https://jsbin.com/bahaxudijo/edit?js,我正在尝试模拟浏览器路由器和路由进行测试,这是我的测试:

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();
});
});
});

但是我嘲笑了错误的浏览器路由器和路由,所以测试通过了,但快照只是空的div。如何正确模拟浏览器路由器和路由?

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(),
};
});

另一种方式:

const rrd = require('react-router-dom');
jest.spyOn(rrd, 'BrowserRouter').mockImplementation(({children}) => children);

来源:

  • https://medium.com/@antonybudianto/react-router-testing-with-jest-and-enzyme-17294fefd303
  • https://stackoverflow.com/a/56565849/1505348
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;

相关内容

  • 没有找到相关文章

最新更新