尝试为我的redux reducer创建一个单元测试。这是reducer,项目被添加到item属性中:
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
我的柴单位测试看起来像这样:
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)
答案 0 :(得分:2)
您可以将带有空数组的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
}
}