我正在为我的简单React + Redux应用程序编写测试,我想知道我究竟如何测试我的Reducer。
我有一个操作,允许用户在单击时从全局状态中删除1个对象,我正在尝试测试它。
这是我的减速机与类型:
const PeopleReducer = (state:any = initialPeopleState, action:any):object => {
switch(action.type){
case DELETE_PERSON:
return {...state, people:state.people?.filter((a:any)=>a.id !== action.id)}
default:
return state;
}
}
下面是我的行动:
export const deletePerson = (id:number) => {
return {
type: DELETE_PERSON,
id
}
}
我用这个命令宣布这次行动:const deleteCard=()=>dispatch(deletePerson(id));
我不知道如何准确地测试这一点,但这是我目前的尝试:
it('should test DELETE Person function', () => {
const deletePerson = {
type: DELETE_PERSON,
id:1
}
expect(reducer({}, deletePerson)).toEqual({people:mockData.people});
});
我的模拟数据基于占位符json API,即用户端点:
export const mockData = {
people: [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}]
}
我如何测试我的deletePerson操作和我的redux删除案例?
1条答案
按热度按时间70gysomp1#
请参阅单元测试单个函数
Reducer是纯函数,在将操作应用到前一个状态后返回新的状态。在大多数情况下,Reducer是一个实现细节,不需要显式测试。但是,如果您的Reducer包含特别复杂的逻辑,您希望对其进行单元测试,那么可以很容易地测试Reducer。
因为reducer是纯函数,所以测试它们应该是直接的。用特定的输入状态和动作调用reducer,并Assert结果状态与期望匹配。
因此,你的测试方法是正确的,但你应该使减速器的输入和输出功能正确。一个工作示例: