如何用Jest-Enzyme测试React的mapStateToProps中handleSave方法并提升覆盖率
如何覆盖mapStateToProps中handleSave方法的测试覆盖率?
你目前的测试只验证了handleSave方法存在,但没有实际执行它内部的逻辑,所以这行代码的覆盖率没被统计到。要解决这个问题,你需要调用这个方法,并验证它的行为是否符合预期,具体步骤如下:
问题代码与现有测试
mapStateToProps代码:
export const mapStateToProps = (state, ownProps) => { return { handleSave: title => ownProps.history.push(setTitle(title)), }; };
现有测试用例:
it('mapStateToProps test case', () => { const result = mapStateToProps(state, ownProps); expect(result.handleSave).toBeTruthy(); });
优化后的测试方案
- 模拟依赖项:先给
ownProps.history.push创建一个模拟函数,方便后续验证调用情况 - 调用handleSave:传入一个测试用的title,执行handleSave方法
- 验证行为:检查
history.push是否被调用,且传入的参数是否是setTitle(title)的正确结果
优化后的测试代码示例:
it('mapStateToProps should return handleSave that triggers history push with setTitle result', () => { // 1. 模拟history.push方法 const mockPush = jest.fn(); const mockOwnProps = { history: { push: mockPush } }; const testTitle = 'Test Title'; // 假设setTitle是已知函数,比如它会返回`/titles/${title}`之类的结果 const expectedPath = setTitle(testTitle); // 2. 获取handleSave并调用它 const result = mapStateToProps({}, mockOwnProps); result.handleSave(testTitle); // 3. 验证行为是否正确 expect(mockPush).toHaveBeenCalledTimes(1); expect(mockPush).toHaveBeenCalledWith(expectedPath); });
这样测试不仅验证了handleSave存在,还实际执行了它内部的箭头函数逻辑,从而覆盖了这行代码的测试覆盖率。
内容的提问来源于stack exchange,提问作者scriobh
相关产品推荐
相关产品推荐

