我正在使用 React 和 Redux。我有一个加载 ChildComponent
的组件,根据 Redux 的状态也将加载 MainComponent
const ChooseIndex = ({ appInitMount }) => {
return (
<>
<ChildComponent />
{!appInitMount && <MainComponent />}
</>
);
};
const mapStateToProps = ({ main }) => {
return {
appInitMount: main.appInitMount
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ChooseIndex);
我正在尝试编写一个测试来检查 ChildComponent
是否已加载:
import React from "react";
import { render } from "react-testing-library";
import ChooseIndex from "../choose-index";
test("ChooseIndex should call ChildComponent", () => {
const wrapper = render(
<ChooseIndex />
);
});
我收到这个错误:
Error: Uncaught [Invariant Violation: Could not find "store" in either the context or props of "Connect(ChooseIndex)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(ChooseIndex)".]
我应该通过将对象字面量传递给 ChooseIndex
来模拟 Redux 吗?或者我应该为每个测试创建一个 Redux 存储(就像我的真实应用程序那样)?
最佳答案
尝试像这样渲染你的组件:
render(
<Provider store={store}>
<ChooseIndex />
</Provider>
)
并传递您在应用中使用的实际商店。通过这种方式,您可以测试将在生产中使用的真实逻辑。您也不关心派发什么 Action 以及状态是什么。您查看渲染的内容并与 UI 交互——这才是最终的重点。
将组件与 Redux 分离并单独测试两者违反了 react-testing-library
的重点。您想像真实用户一样测试您的应用。
关于reactjs - 在测试 React 组件时模拟 Redux 存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52981031/