【发布时间】:2020-03-03 21:02:55
【问题描述】:
我的 ReactJS 项目中的 jest/enzyme 单元测试有问题,我将我的组件转换为 ES6 并使用钩子将我的 redux 连接到减速器存储。然而,在这个组件中添加了使用钩子的更改之后,它的单元测试已经被破坏了,我花了几天时间试图弄清楚为什么这个测试将不再浅渲染,因为完全安装可以正常工作。
DemoPage.js
import React from 'react';
import { useSelector, useDispatch} from 'react-redux';
import * as actions from '../../actions/demoPageActions';
import DemoPageForm from '../demoApp/DemoPageForm';
import {compose} from "recompose";
import {withStyles} from "@material-ui/core";
const styles = theme => ({});
export const DemoPage = () => {
const demoState = useSelector(state => state.demoPage);
const dispatch = useDispatch();
const saveSomething = () => {
dispatch(actions.saveSomething(demoState));
};
const calculateSomething = e => {
dispatch(actions.calculateSomething(demoState, e.target.name, e.target.value));
};
return (
<DemoPageForm
onSaveClick={saveSomething}
onChange={calculateSomething}
demoState={demoState}
/>
);
};
export default compose(withStyles(styles))(DemoPage);
DemoPage.spec.js
import React from "react";
import { shallow } from "enzyme";
import {DemoPage} from "./DemoPage";
import DemoPageForm from "../demoApp/DemoPageForm";
describe("<DemoPage />", () => {
it("should contain <DemoPageForm />", () => {
const wrapper = shallow(
<DemoPage/>
);
expect(wrapper.find(DemoPageForm).length).toEqual(1);
});
});
这会产生以下错误
<DemoPage /> › should contain <DemoPageForm />
Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>
9 |
10 | export const DemoPage = () => {
> 11 | const demoState = useSelector(state => state.demoPage);
| ^
12 | const dispatch = useDispatch();
13 |
14 | const saveSomething = () => {
这非常令人困惑,因为它仍然应该测试未连接的组件,但是我相信 useSelector 的钩子会导致这个问题,所以在阅读了大约 30-40 页有关这些内容的内容后,我还没有找到最接近的解决方案我得到的是使用挂载,它工作得很好,但是我更喜欢这个测试的浅层,这是包装在带有模拟存储的提供程序中时的代码和结果
describe("<DemoPage />", () => {
const mockStore = configureMockStore()
const store = mockStore(returnInitialState());
it("should contain <DemoPageForm />", () => {
const wrapper = shallow(
<Provider store={store}>
<DemoPage
store={store}
/>
</Provider>
);
console.log(wrapper.dive().debug())
expect(wrapper.find(DemoPageForm).length).toEqual(1);
});
});
console.log src/components/containers/DemoPage.spec.js:23
<DemoPage store={{...}} />
● <DemoPage /> › should contain <DemoPageForm />
expect(received).toEqual(expected) // deep equality
Expected: 1
Received: 0
23 | console.log(wrapper.dive().debug())
24 |
> 25 | expect(wrapper.find(DemoPageForm).length).toEqual(1);
| ^
26 | });
27 | });
如果有人知道如何解决这个问题,那将非常有帮助。干杯
【问题讨论】:
标签: reactjs redux react-redux enzyme