我正在进行减速器测试,当我尝试测试我的动作类型之一时,期望值和接收值不匹配。
eventReducer.test.js
import reducer from './eventReducer';
import { GET_EVENTS } from '../actions/types';
describe('event reducer', () => {
it('should return initial state', () => {
expect(reducer(undefined, {})).toEqual({
eventDetails: [],
loading: false
});
})
it('should store data from db upon mounting component', () =>{
expect(reducer({}, {
type: GET_EVENTS,
eventDetails: [
{
firstName: 'Damian',
lastName: 'Wasilewski'
}
]
})
).toEqual({
eventDetails: [
{
firstName: 'Damian',
lastName: 'Wasilewski'
}
],
loading: false
})
});
})
eventReducer.js
import { GET_EVENTS, ADD_EVENT, DELETE_EVENT, EVENTS_LOADING } from '../actions/types';
const initialState = {
eventDetails: [],
loading: false
}
export default function (state = initialState, action) {
switch(action.type) {
case GET_EVENTS:
return {
...state,
eventDetails: action.payload,
loading: false
};
case DELETE_EVENT:
return {
...state,
eventDetails: state.eventDetails.filter(event => event._id !==
action.payload)
};
case ADD_EVENT:
return {
...state,
eventDetails: [action.payload, ...state.eventDetails]
};
case EVENTS_LOADING:
return {
...state,
loading: true
}
default:
return state;
}
}
我的第一个测试运行正常,但是当我尝试执行第二个测试时,它与接收到的值和预期值不匹配,问题出在eventDetails数组上,它不断输出其值未定义。
测试输出
FAIL src/reducers/eventReducer.test.js
● event reducer › should store data from db upon mounting component
expect(received).toEqual(expected)
Expected value to equal:
{"eventDetails": [{"firstName": "Damian", "lastName": "Wasilewski"}], "loading": false}
Received:
{"eventDetails": undefined, "loading": false}
Difference:
- Expected
+ Received
Object {
- "eventDetails": Array [
- Object {
- "firstName": "Damian",
- "lastName": "Wasilewski",
- },
- ],
+ "eventDetails": undefined,
"loading": false,
}
21 | ]
22 | })
> 23 | ).toEqual({
| ^
24 | eventDetails: [
25 | {
26 | firstName: 'Damian',
at Object.toEqual (src/reducers/eventReducer.test.js:23:5)
什么会导致未定义数组的问题?
答案 0 :(得分:0)
您正在将event.details设置为action.payload,但在测试中,您并未发送有效负载属性。
it('should store data from db upon mounting component', () =>{
expect(reducer({}, {
type: GET_EVENTS,
payload: [
{
firstName: 'Damian',
lastName: 'Wasilewski'
}
]
})
).toEqual({
eventDetails: [
{
firstName: 'Damian',
lastName: 'Wasilewski'
}
],
loading: false
})
});
})
这应该可以解决您的问题