簡體   English   中英

如何使用React和Redux測試具有嵌套容器的組件?

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

由於我正在處理的應用程序的復雜性,我決定使用嵌套的redux容器,而不是將一個動作作為prop傳遞給子組件。 然而,當使用jsdom結合mochachaisinon渲染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)". 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>
    );

export default root;

希望有人幫助!

模擬Provider組件以返回子組件。

describe()之前添加它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM