gpt4 book ai didi

javascript - 使用 Jest 和 Enzyme 测试 react-router v4

转载 作者:可可西里 更新时间:2023-11-01 02:40:52 25 4
gpt4 key购买 nike

我有一个简单的应用程序,他们使用 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>
);

和测试

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

为什么这个测试失败了? enter image description here

我的配置:

  • enzyme :2.8.2
  • react 脚本:1.0.7
  • react 测试渲染器:15.5.4

最佳答案

您必须提供initialEntries 以及initialIndex。在您的情况下,它应该如下所示:

const wrapper = shallow(
<MemoryRouter initialEntries={['/']} initialIndex={0}>
<App/>
</MemoryRouter>
);

另一种可能性是您需要 enzyme mount而不是shallow

react-router 这里有一些很棒的文档: https://reacttraining.com/react-router/core/api/MemoryRouter

关于javascript - 使用 Jest 和 Enzyme 测试 react-router v4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44441852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com