Jest测试中出现addEventListener未定义错误的原因排查
问题
我尝试测试以下React组件代码:
componentDidMount() { this.refdInput.addEventListener("fieldInput", this.onChange); this.refdInput.addEventListener("fieldInput", this.onBlur); this.refdInput.addEventListener("fieldInput", this.onFocus); } <input id="float-input-component" type="text" className={classes.join(" ")} ref={elem => {this.refdInput = elem;}} />
在spec.ts中编写了测试代码:
var el = document.getElementById("float-input-component"); el.addEventListener('fieldInput', onChange()); el.addEventListener('fieldInput', onBlur()); el.addEventListener('fieldInput', onFocus());
运行测试后抛出错误:TypeError: Cannot read property 'addEventListener' of undefined,请问我哪里做错了?
错误原因及修正方案
- DOM元素未完成挂载就查询:测试代码中直接调用
document.getElementById时,组件可能还没渲染到DOM中,导致el返回undefined。React测试里必须确保组件完成渲染后再操作DOM,比如用测试库的waitFor或findBy*方法等待元素出现。 - 事件回调传递错误:你写的
onChange()是直接执行了函数,把执行结果(通常是undefined)绑定给了事件,正确的做法是传递函数引用onChange(不带括号)。
下面是修正后的测试示例(以React Testing Library为例):
import { render, waitFor } from '@testing-library/react'; import YourComponent from './YourComponent'; test('验证fieldInput事件绑定', async () => { // 模拟回调函数 const onChange = jest.fn(); const onBlur = jest.fn(); const onFocus = jest.fn(); // 渲染组件 render(<YourComponent onChange={onChange} onBlur={onBlur} onFocus={onFocus} />); // 等待元素挂载到DOM const el = await waitFor(() => document.getElementById("float-input-component")); // 触发自定义fieldInput事件 el.dispatchEvent(new CustomEvent('fieldInput')); // 断言回调函数被调用 expect(onChange).toHaveBeenCalled(); expect(onBlur).toHaveBeenCalled(); expect(onFocus).toHaveBeenCalled(); });
内容的提问来源于stack exchange,提问作者rozjni
相关产品推荐
相关产品推荐

