![](/img/trans.png)
[英]How to write a test case for a simple React component using Jest and Enzyme
[英]How to write unit test case for componentDidMount() and export default connect(null, updateProps)(<ComponentName>) with JEST/Enzyme in React?
我創建了簡單的反應組件並編寫了正常工作的組件的測試用例。 我有測試用例的覆蓋率報告。
現在,我在我的其他組件中添加了 react redux。 該組件包含 componentDidMount() 和導出默認的 connect(null, updateProps)(ComponentName) 方法。 我需要為這些方法編寫單元測試用例。
請參考以下代碼示例,
class MyComponent extends Component {
componentDidMount = () => {
//some code here
)
handleSignIn = (e) => {
//some code here
}
render() {
return (
<div>
<form onSubmit={this.handleSignIn}>
<Input
type="text"
name="inputText"
placeholder="Text"
autoFocus
required
/>
</form>
</div>
);
}
const updateProps = (dispatch) => {
return {
//some code here
};
};
export default connect(null, updateProps)(MyComponent);
在您的代碼中,您有兩件事:
class MyComponent
和
const thisIsBasicallyAnotherComponent = connect(null, updateProps)(MyComponent);
所以如果你想測試你的組件,你基本上有兩個選擇。 您可以測試包裝並連接到 redux 存儲的組件,也可以按原樣為 class 組件編寫簡單的單元測試。
我建議做的是導出您的 class 組件
- class MyComponent extends Component { // replace this
+ export class MyComponent extends Component { // with this
然后你可以像任何其他組件一樣使用 Jest 測試你的 React 組件。
test('Link changes the class when hovered', () => {
const component = renderer.create(
<MyComponent {...mockProps} /> // !! keep in mind that you have to manually pass what you have in `updateProps` because the component is not connected to Redux store anymore
);
// ... write your test and expectations here
});
否則,您可以測試您連接的組件(默認導出的內容),但是您必須將組件包裝在 Redux 提供程序中才能對其進行測試。
您可以在此處找到有關測試的更多信息:
您可以使用react-redux
或redux-mock-store
Provider
來避免需要使用真正的 reducer:
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import MyComponent from './MyComponent.jsx';
const mockStore = configureStore([thunk]);
it('does something on mount', () => {
// let's mock some Redux state
const store = mockStore({ slice1: { id: 2, name: '11' } });
mount(<Provider store={store}><MyComponent /></Provider>);
expect(store.getActions()).toContainEqual({
type: 'some-type',
payload: ....
});
});
但這只是簡單的動作。 如果你使用redux-thunk
並且有一些加載怎么辦? 有2種方式:
redux-thunk
中間件傳遞給mockStore
和模擬網絡,例如,使用mock-fetch
或nock
。 設置起來更容易,但如果您已經直接測試了 Redux,那么對您的組件重復測試“加載失敗”、“加載需要很長時間”等也意味着雙重工作。../yourPath/actions.js
,這樣每個操作都會是普通的 object,而不是 thunk。 我通常以這種方式使用 go。 但是“導出未包裝的組件以便我們可以在沒有 Redux 的情況下單獨測試組件”呢? 你看,當connect
是唯一可能的 API 時,它正在工作。 但是現在考慮到useSelector
、 useDispatch
、 useStore
類的鈎子,首先對“my component IN Redux”進行測試更加可靠。 否則,使用“雙重導出”方法,我們可能會發現,將組件從 class 轉換為 function 意味着更多的修補測試工作,而不是組件本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.