【问题标题】:Enzyme test for empty array on componentWillUnMount dispatch actioncomponentWillUnMount 调度操作上的空数组的酶测试
【发布时间】:2019-04-13 19:05:24
【问题描述】:

我正在尝试通过在对 componentWillUnMount 进行调度和操作时检查容器上的 props 来测试 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"] 数组,而不是预期的空数组。

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    它令人困惑,因为您也有所有大写的 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;
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多