如何使用 React 和 Redux 测试带有嵌套容器的组件?

How to test a component with a nested container with React and Redux?

由于我正在处理的应用程序的复杂性,我决定使用嵌套的 redux 容器,而不是将操作作为道具传递给子组件。但是,这已证明在使用 jsdommochachaisinon 结合呈现 OuterContainer 时,单元测试会出现问题。

这是视图结构的人为示例:

<OuterContainer>
  <div>
    <InnerContainer />
  </div>
</OuterContainer>

其中 OuterContainerInnerContainer 包含连接。例如:

export connect(<mapStateToProps>)(<Component>)

当 运行 测试我得到的错误是: Invariant Violation: Could not find "store" in either the context or props of "Connect(Component)". Either wrap the root component in a `<Provider>`, or explicitly pass "store" as a prop to "Connect(Component)".

有没有办法在不使用浅层渲染的情况下解包或存根 InnerContainer 进行单元测试?

测试时将您的组件包裹在 <Provider> 中。由您决定是提供一个真实的商店还是一个带有 { dispatch, getState, subscribe } 的模拟。将最外层组件包装在 <Provider store={store}> 中还将使商店可供任何嵌套级别的子组件使用——就像在应用程序本身中一样。

const store = createStore(reducer) // can also be a mock
ReactTestUtils.renderIntoDocument(
  <Provider store={store}>
    <OuterContainer />
  </Provider>
)

另一种方法是将要连接的组件和容器都导出。当然是默认的容器。

export const Comp = (props) => (<p>Whatever</p>)
export default connect(...)(Comp)

因此,您可以进行单元测试 Comp

不确定这是否是您的问题所在,但我相信这可能会对查看此提要的一些人有所帮助。

我有同样的错误,这是一个简单的修复:

我忘记在我的入口文件中传递我的组件我的存储对象(使用 webpack)。

我刚刚向 Root 组件添加了一个属性 "store={store}" 见下文:

    document.addEventListener("DOMContentLoaded", () => {
      const store = configureStore();
       ReactDOM.render(<Root store={store} />, 
     document.getElementById('content'));
    });

这也是我的根文件代码,供参考:

    import React from 'react';
    import { Provider } from 'react-redux';
    import App from './app';

    const Root = ({ store }) => (
     <Provider store={ store }>
        <App />
     </Provider>
    );

导出默认根;

希望对某人有所帮助!

Provider 组件模拟为 return 子组件。

describe()之前添加这个。

jest.mock('Provider', () => ({children}) => children);