如何用Jest/Enzyme测试React组件onFocus函数的未覆盖分支?
解决Form组件onFocus函数的测试覆盖率问题
你的问题很清晰:onFocus函数里有个未被覆盖的逻辑分支——当组件无error状态时触发focus事件的场景没被测试到,导致覆盖率报告出现未覆盖提示。咱们直接来补全这个测试:
先拆解onFocus的逻辑
先看组件里的onFocus代码:
onFocus = () => !isEmpty(this.state.error) && this.setState({ ...this.state, error: '' });
这是个短路逻辑:只有当error不为空时,才会执行setState清除错误;如果error本来就是空的,!isEmpty(...)返回false,后面的setState不会执行——这就是你遗漏的未覆盖分支。
补充测试用例
在你的测试文件中,已经覆盖了「有error时清除错误」的场景,现在只需要在同一个describe块里新增一个测试用例,覆盖「无error时触发focus」的分支:
修改后的完整测试文件代码:
import React from "react"; import { mount } from 'enzyme'; import Form from "../../../layout/navbar/Form"; const setComponent = (props) => { const component = mount(<Form {...props} />); return component; } describe("Navbar `Form` component", () => { let component; beforeEach(() => { component = setComponent(); }); it('Renders without errors', () => { expect(component).toMatchSnapshot(); }); describe('`onFocus` func call behavior', () => { it('Clears the error state if any exists', () => { component.find(`button[type='submit']`).simulate('click'); component.find(`[data-test='input']`).simulate('focus'); expect(component.state().error).toEqual(''); }); it('Does nothing when there is no existing error', () => { // 先确认初始状态error为空 expect(component.state().error).toEqual(''); // 触发input的focus事件 component.find(`[data-test='input']`).simulate('focus'); // 验证error状态未发生变化(未执行setState) expect(component.state().error).toEqual(''); }); }); });
说明一下改动点
- 我把原来的describe标题从
'onFocusfunc call to clear errors'改成了'onFocusfunc call behavior',这样更贴合两个测试用例的场景,逻辑更连贯。 - 新增的测试用例先确认组件初始状态下
error是空的,触发focus后再验证error状态没有变化——完美覆盖了onFocus函数里「无error时不执行任何操作」的分支。
补完这个测试后,你的onFocus函数所有分支就都被覆盖了,覆盖率报告里的未覆盖提示应该就消失了。
内容的提问来源于stack exchange,提问作者Text Error
相关产品推荐
相关产品推荐

