React中用Jest+Enzyme测试toggleFilter函数遇问题求助
第一个错误:TypeError: Cannot read property 'includes' of undefined
这个错误的核心原因是你调用toggleFilter的参数和原函数定义不匹配。
你的原toggleFilter函数明确接受两个参数:
toggleFilter = (filterType, filterName) => { ... }
但在测试代码里,你传入的是一个模拟的事件对象:
component.find(FilterDropdownContent).prop("toggleFilter")({ target: { value: "someValue" } });
这会导致:
filterType被赋值为这个事件对象(而非你期望的"access"、"bandwidth"这类字符串)filterName变成undefined
当函数执行到this.state.appliedFilterList[filterType]时,用对象作为键去访问appliedFilterList自然找不到对应属性,结果就是undefined,调用includes方法就会抛出上述错误。
修复方案
按照原函数的参数要求,传入filterType和filterName两个参数,比如测试添加access类型下的"a 1"过滤器:
// 替换原来的调用代码 component.find(FilterDropdownContent).prop("toggleFilter")("access", "a 1");
第二个错误:Mock函数未按预期调用
你的测试断言expect(toggleFilterMockFn).toHaveBeenCalledWith(appliedFilter, "access");是错误的,因为:
原toggleFilter函数的参数是filterType和filterName,appliedFilterList是组件内部的state,并不是函数的入参。你把appliedFilter作为调用参数传入断言,和实际函数的调用逻辑完全不符,所以断言失败。
修复方案
调整断言,检查mock函数是否被传入了正确的filterType和filterName参数,对应上面的调用,断言应该是:
expect(toggleFilterMockFn).toHaveBeenCalledWith("access", "a 1");
另外还要确保测试用例中appliedFilter的结构和组件state要求一致,比如每个filterType对应的数组都存在(例如{ access: [], bandwidth: [], terms: [] }),避免在真实函数执行时(如果不用mock的话)出现类似的undefined问题。
内容的提问来源于stack exchange,提问作者pranami

