首页 > 解决方案 > 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"] 数组,而不是预期的空数组。

标签: reactjsjestjsenzyme

解决方案


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

推荐阅读