[英]How to test a React component that has Router, Redux and two HOCs… with Jest and Enzyme?
I am currently unable to find a solution to this problem. 我目前无法找到解决此问题的方法。 I have a React Component that is connected to React Router 4, Redux store and is wrapped by two HOCs.
我有一个React组件连接到React Router 4,Redux存储并由两个HOC包装。 Its pretty crazy, but this is how it was coded.
它非常疯狂,但这是它的编码方式。 Here is the export to give you an idea:
这是出口给你一个想法:
export default withFetch(Component)(fetchData, mapStateToProps)
I am trying to run some basic tests on it: 我正在尝试对它进行一些基本测试:
it('should render self and subcomponents', () => {
const wrapper = shallow(<Component {...props} />)
expect(toJson(wrapper)).toMatchSnapshot()
})
Which outputs a console.log/snapshot of: 其中输出一个console.log / snapshot:
<Route render={[Function: render]} />
Things tried but no succeed: 事情尝试但没有成功:
Memory Router
Memory Router
.dive()
and .chilndren()
to try and see the children .dive()
和.chilndren()
来尝试查看孩子们 mount
and render
with no success. mount
和render
没有成功。 Still keeps rendering the <Route render={[Function: render]} />
仍然保持渲染
<Route render={[Function: render]} />
Trying out : 尝试 :
<MemoryRouter>
<Component {...props} />
</MemoryRouter>
Still produces the same result. 仍然产生相同的结果。 Note that I've also tried importing my component as
请注意,我也尝试将我的组件导入为
import { Component } from './components/'
But it returns undefined. 但它返回undefined。
Any help is deeply appreciated. 非常感谢任何帮助。 Thank you!
谢谢! 😊🙏
😊🙏
I assume that by <Router>
you are referring to BrowserRouter. 我假设通过
<Router>
你指的是BrowserRouter。 The best way is to isolate the wrapped component and test it with testing alternatives. 最好的方法是隔离包裹的组件并使用测试替代方案对其进行测试。
For example assume that you want to test that: 例如,假设您要测试:
// App.jsx
export const App = () =>
<Router>
<ReduxProvider>
<AppInner>
</ReduxProvider>
</Router>
My suggestion is to test AppInner
with testing env of Router & ReduxProvider. 我的建议是使用Router&ReduxProvider的测试
AppInner
测试AppInner。
In tests: 在测试中:
// AppInner.test.jsx
import {mount} from 'enzyme';
import {MemoryRouter} from 'react-router';
describe('AppInner', () => {
it('should do something', () => {
const TestingComponent = () =>
<MemoryRouter>
<ReduxProvider>
<AppInner />
<ReduxProvider>
<MemoryRouter>;
const component = mount(TestingComponent);
});
})
Pay attention that I've wrapped the AppInner
with MemoryRouter
, it allows your mimic router but without the dependency of the browser. 注意我已经将
AppInner
与MemoryRouter
包装MemoryRouter
,它允许你的模拟路由器但没有浏览器的依赖。
For more info you can read the testing
section of react-router
; 有关更多信息,您可以阅读
react-router
的testing
部分;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.