如何让减速器单元测试工作?

How to get reducer unit test working?

正在尝试为购物车的 redux reducer 创建单元测试。这是减速器,项目被添加到项目 属性:

    const initialState = {
    items: [],
    cartOpen: false,
    newMonthlyCost: 0,
    currentMonthlyCost: 0,
    showNextButton: false,
    orderConfirmed: false
}

const Cart = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            return Object.assign({}, state,
                {
                    items: [...state.items,action.data]
                });

        default:
            return state
    }
}


export default Cart

我的 chai 单元测试是这样的:

import reducer from './../../foss-frontend/app/reducers/cart.js'
import {expect} from 'chai';

describe('cart reducer', () => {

    it('should handle ADD_TO_CART', () => {
        expect(
            reducer([], {
                type: 'ADD_TO_CART',
                data: {
                    id: 12, price: 2332
                }
            })
        ).to.deep.equal({items: [{id: 124, price: 2332}]})
    })
})

为什么会出现此错误以及如何解决?

错误:

     TypeError: Cannot convert undefined or null to object
      at Function.from (native)
      at _toConsumableArray (app\reducers\cart.js:7:182)

您在 tetsts 调用 reducer,状态为空数组

reducer([], {...})

因此 state.items 未定义。然后你尝试解构它

items: [...state.items,action.data]

并得到这个错误。

请检查 state.items 是否存在 - 例如这样

const Cart = (state = initialState, action) => {
    switch (action.type) {
        case 'ADD_TO_CART':
            const { items=[] } = state;
            return Object.assign({}, state,
                {
                    items: [...items,action.data]
                });

        default:
            return state
    }
}