reactjs - componentWillUnMount 调度操作上的空数组的酶测试
问题描述
我正在尝试通过在对 componentWillUnMount 进行调度和操作时检查容器上的道具来测试 redux 存储是否更改为空数组。
所以我的意思是,测试从我的 redux reducer 到空数组的更改 ["foo", "bar"] []
。
我的代码如下所示:
容器:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../store/actions/actions';
class MyComponent extends Component{
componentWillUnmount(){
this.props.cleanSearch();
}
render(){
return(
<div>
Whatever
</div>
)
}
}
const mapStateToProps = state=>{
const itemsSearched = state.itemsSearched;
return{
itemsSearched
}
}
const mapDispatchToProps = dispatch =>{
return{
cleanSearch: ()=> dispatch(actions.cleanSearch())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
我的减速机:
import {
CLEAN_SEARCH
} from '../actions/types';
import * as utils from '../../utils/udpaterState';
const initialState = {
itemsSearched: ["foo", "bar"]
}
const reducer= (prevState = initialState, action)=>{
let newState = null;
switch(action.type){
case CLEAN_SEARCH:
newState = {itemsSearched: []}
return utils.updaterState(prevState, newState);
default:
return prevState;
}
}
export default reducer;
我的测试代码如下所示:
MyComponent.test.js
it('cleans redux prop searches when componentWillUnMount is called', ()=>{
const spy = jest.spyOn(MyComponent.prototype, 'componentWillUnmount');
const wrapper = mount(<MyComponent store={storeUtil} itemsSearched={mocks.itemsSearched()} />);
expect(wrapper.props().itemsSearched).toEqual(mocks.itemsSearched());
wrapper.instance().componentWillUnmount();
expect(wrapper.props().itemsSearched).toEqual([]);
})
但是,我收到的是 ["foo", "bar"] 数组,而不是预期的空数组。
解决方案
它令人困惑,因为你也有所有大写的 CLASS_CASE 和 camelCase ......开关案例不应该是 cleanSearch 而不是 case CLEAN_SEARCH 因为你是这样调用它的mapDispatchToProps
:
import {
CLEAN_SEARCH
} from '../actions/types';
import * as utils from '../../utils/udpaterState';
const initialState = {
itemsSearched: ["foo", "bar"]
}
const reducer= (prevState = initialState, action)=>{
let newState = null;
switch(action.type){
case cleanSearch:
newState = {itemsSearched: []}
return utils.updaterState(prevState, newState);
default:
return prevState;
}
}
export default reducer;
推荐阅读
- vuejs2 - Vue.js 2:状态变量更改时的操作
- android - Send sensor data from Wear OS to laptop in realtime
- docker - 将 docker 映像部署到 Kubernetes Engine 时权限被拒绝
- php - Proxy Error - I don't think I am running a proxy
- java - 如何抑制特定的 Kotlinc/Javac 编译器警告?
- swift - 检测视频剪辑是否受复制保护
- sql - 加快 SSIS 中的表查询
- java - Java:获取存储在链接列表中的字符串的 char 索引元素
- python - 忽略 ssl 证书以便于安装 python
- c++ - Helgrind 和 atomic_flag