【问题标题】:How to get reducer unit test working?如何让减速器单元测试工作?
【发布时间】:2016-12-16 08:43:48
【问题描述】:

尝试为我的购物车 redux reducer 创建一个单元测试。这是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)

【问题讨论】:

  • 您的代码看起来不错。我猜错误在你没有发布的部分。能把reducer的所有代码贴出来测试一下吗?
  • 嗨 Artem 见上文
  • .to.deep.equal({items: {id: 124, price: 2332}}) 应该是 .to.deep.equal({items: [ {id: 124, price: 2332} ] })
  • 好皮卡,但还是同样的错误

标签: unit-testing reactjs react-redux chai


【解决方案1】:

你在 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
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
相关资源
最近更新 更多