如何用Jest测试React+Redux的deletePerson动作与Reducer删除分支
正确测试Redux Reducer的删除逻辑
核心思路
测试Reducer的关键是固定初始状态和动作,验证输出的新状态符合预期——Reducer是纯函数,不需要涉及dispatch或组件,直接测试其输入输出逻辑即可。
你的测试问题分析
当前测试存在两个核心问题:
- 初始状态传了空对象
{},不符合真实业务场景(真实状态应该包含people数组) - 预期结果写的是
{people:mockData.people},和删除动作的预期完全相反(删除id=1的用户后,people应该是空数组)
正确的测试代码
基础删除逻辑测试
import { PeopleReducer, DELETE_PERSON } from './your-reducer-path'; import { mockData } from './your-mock-data-path'; it('should remove the target person when receiving DELETE_PERSON action', () => { // 1. 准备包含目标用户的初始状态 const initialState = { ...mockData }; // 2. 创建删除动作(可直接用action creator或手动定义) const deleteAction = { type: DELETE_PERSON, id: 1 }; // 3. 调用Reducer生成新状态 const newState = PeopleReducer(initialState, deleteAction); // 4. 断言结果符合预期 expect(newState.people).toEqual([]); // 额外断言:新状态是全新对象,未修改原状态(Redux reducer必须保持纯函数特性) expect(newState).not.toBe(initialState); });
边界场景测试
为保证Reducer健壮性,需覆盖异常场景:
it('should return original state when deleting a non-existent id', () => { const initialState = { ...mockData }; const deleteAction = { type: DELETE_PERSON, id: 999 }; const newState = PeopleReducer(initialState, deleteAction); // 状态无变化 expect(newState).toEqual(initialState); }); it('should handle empty initial state gracefully', () => { const deleteAction = { type: DELETE_PERSON, id: 1 }; const newState = PeopleReducer({}, deleteAction); // 因原状态无people属性,处理后people为undefined(对应你的可选链逻辑) expect(newState.people).toBeUndefined(); });
可选:Action Creator单独测试
如果需要验证deletePerson动作生成器的正确性:
import { deletePerson, DELETE_PERSON } from './your-action-path'; it('should generate DELETE_PERSON action with correct id', () => { const testId = 5; const action = deletePerson(testId); expect(action).toEqual({ type: DELETE_PERSON, id: testId }); });
内容的提问来源于stack exchange,提问作者andorando
相关产品推荐
相关产品推荐

