在测试 React 组件时模拟 Redux 存储?

Mocking Redux store when testing React components?

我正在使用 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 存储(就像我的真实应用程序那样)?

如果您查看 redux 文档的 writing tests 部分,这里有一个测试连接组件的示例。

when you import it [A redux connected component], you're actually holding the wrapper component returned by connect(), and not the App component itself. If you want to test its interaction with Redux, this is good news: you can wrap it in a with a store created specifically for this unit test. But sometimes you want to test just the rendering of the component, without a Redux store.

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component

与大多数单元测试一样,您确实想要测试您的组件,而不是 redux 是否正常工作。所以你的解决方案是导出组件和连接的组件,同时只测试组件本身,并提供 redux 传递给你的组件的任何道具。

import { connect } from 'react-redux'

// Use named export for unconnected component (for tests)
export class App extends Component {
  /* ... */
}

// Use default export for the connected component (for app)
export default connect(mapStateToProps)(App)

尝试像这样呈现您的组件:

render(
  <Provider store={store}>
    <ChooseIndex />
  </Provider>
)

并传递您在应用中使用的实际商店。通过这种方式,您可以测试将在生产中使用的真实逻辑。您也不关心派发什么动作以及状态是什么。您查看渲染的内容并与 UI 交互——这才是最重要的。

将组件与 Redux 分离并单独测试两者违反了 react-testing-library 的重点。您想像真实用户一样测试您的应用。