![](/img/trans.png)
[英]How to test component that contains a component connected to Redux in Enzyme / React?
[英]How to test a component with a nested container with React and Redux?
由於我正在處理的應用程序的復雜性,我決定使用嵌套的redux容器,而不是將一個動作作為prop傳遞給子組件。 然而,當使用jsdom結合mocha
, chai
和sinon
渲染OuterContainer
時,這證明對於單元測試是有問題的。
這是一個人為的視圖結構示例:
<OuterContainer>
<div>
<InnerContainer />
</div>
</OuterContainer>
其中OuterContainer
和InnerContainer
用連接包裹。 例如:
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.