簡體   English   中英

酶/Jest 反應測試 - 具有 react-redux > 6 的淺連接組件

[英]Enzyme/Jest React Testing - Shallow connected component with react-redux > 6

我們使用 Enzyme 和 Jest 進行測試。 在我們的代碼庫中更新到最新版本的 react-redux,並且所有連接的組件測試用例開始失敗(版本 6)。 使用

import { createMockStore } from 'redux-test-utils';

創建商店

適用於舊版本的測試用例:

const wrapper = shallow(<SomeConnectedComponent />, {context: { store }});

這失敗給出錯誤

不變違規:在“Connect(SomeConnectedComponent)”的上下文中找不到“store”。

閱讀了幾篇文章,得到了使用提供程序包裝器安裝和包裝的建議

const wrapper = mount(<Provider store={store}><SomeConnectedComponent /></Provider>);

上面的代碼有效,但我希望它與吞咽一起用於單元測試。

編輯 :

const wrapper = shallow(<Provider store={store}>
<SomeConnectedComponent />
</Provider>)

上面的代碼返回空的shallowWraper 對象。

使用 react-redux 版本 > 6 吞下連接組件的最佳方法是什么

Shallow 不適用於最新版本的 react-redux。 從版本 6.x 開始,它會導致上述問題。

我發現的最佳解決方案是使用舊版本的 react-redux 進行測試,使用較新的版本進行實際代碼。

1)將舊版本添加為開發依賴項。 因為有較新版本的 react-redux,所以您需要使用別名。 這可以是任何版本 5.x 這將安裝“react-redux-test”

yarn add react-redux-test@npm:react-redux@5.0.6 -D

2) 在 _ mocks _ 文件夾下,創建一個新文件 react-redux.js 並從里面導出舊版本

export * from 'react-redux-test';

默認情況下,這個模擬將在每個測試用例文件中使用,因此舊的測試代碼不再中斷。

但是,如果您想使用新的 react-redux 庫進行測試,則可以使用

jest.unmock('react-redux')

在新的測試文件上方。

升級后有數百個測試失敗,這種方法對我有用,因為我也想在新組件中使用 Hooks Api。

通過這種方式,您可以使用新庫的功能,直到酶 / react-redux 提出修復方案。

淺在 redux 7 上確實有效,但實現發生了變化。 所以而不是

const wrapper = shallow(<Provider store={store <SomeConnectedComponent/></Provider>)

你現在做

const wrapper = shallow(<SomeConnectedComponent store={store}/>)

不再需要包裝提供者,並防止不必要的潛水。 然后,您可以像這樣遍歷淺層包裝器:

wrapper.children().dive().find(<ChildComponent>))

暫無
暫無

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

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