我对测试完全陌生。现在,我正在尝试测试routre。 如何正确测试? Register.js
import React from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import user from "./user";
import employee from "./employee";
const Registers = ({ match }) => (
<div className="dashboard-wrapper">
<Switch>
<Redirect exact from={`${match.url}/`} to={`${match.url}/user`} />
<Route path={`${match.url}/user`} component={user} />
<Route path={`${match.url}/employee`} component={employee} />
<Redirect to="/error" />
</Switch>
</div>
);
export default Registers;
试图以此方式进行测试。
Enzyme.configure({ adapter: new Adapter() });
test('invalid path should redirect to 404', () => {
const wrapper = mount(
<MemoryRouter initialEntries={[ '/user' ]}>
<Registers/>
</MemoryRouter>
);
expect(wrapper.find(user)).toHaveLength(0);
expect(wrapper.find(employee)).toHaveLength(1);
});
答案 0 :(得分:1)
在路径上模拟浏览器路由器
" __mocks__/react-router-dom.js "
import React from 'react';
const rrd = require('react-router-dom');
// Just render plain div with its children
rrd.BrowserRouter = ({children}) => <div>{children}</div>
module.exports = rrd;
测试方式
test('invalid path should redirect to 404', () => {
const wrapper = mount(
<MemoryRouter initialEntries={[ '/user' ]}>
<App/>
</MemoryRouter>
);
expect(wrapper.find(user)).toHaveLength(0);
expect(wrapper.find(employee)).toHaveLength(1);
});