Pav*_*vel 11 javascript reactjs jestjs enzyme react-router-v4
我有一个简单的应用程序,他们使用react-router v4
const App = () => (
<Switch>
<Route exact path="/" component={() => <div>Home</div>}/>
<Route path="/profile" component={() => <div>Profile</div>}/>
<Route path="/help" component={() => <div>Help</div>}/>
</Switch>
);
Run Code Online (Sandbox Code Playgroud)
并测试
jest.dontMock('../App');
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { shallow } from 'enzyme';
import App from '../App';
describe('<App />', () => {
const wrapper = shallow(
<MemoryRouter>
<App/>
</MemoryRouter>
);
console.log(wrapper.html());
it('renders a static text', () => {
expect(
wrapper.contains(<div>Home</div>)
).toBe(true);
});
});
Run Code Online (Sandbox Code Playgroud)
我的配置:
你必须提供initialEntries以及initialIndex.在你的情况下,它应该是这样的:
const wrapper = shallow(
<MemoryRouter initialEntries={['/']} initialIndex={0}>
<App/>
</MemoryRouter>
);
Run Code Online (Sandbox Code Playgroud)
另一种可能性是,你需要enzyme的mount不是shallow.
react-router这里有一些很棒的文档:https:
//reacttraining.com/react-router/core/api/MemoryRouter