对componentWillUnMount调度操作上的空数组进行酶测试

时间:2018-11-10 12:10:12

标签: reactjs jestjs enzyme

我试图通过检查容器上的props以及对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”]数组,而不是空的预期数组。

1 个答案:

答案 0 :(得分:0)

它令人困惑,因为您也都拥有CLASS_CASE和camelCase的大写字母...开关的大小写不应该是cleanSearch,而大小写不应该是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;