You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决StencilJS组件自定义focusEvent事件E2E测试触发失败问题

错误原因

  • 你自定义的focusEvent是<my-textbox>组件触发的,不是内部原生input元素触发的,给input绑定事件监听自然监听不到。
  • 你调用的toHaveBeenCalled()是Jest针对mock函数的匹配器,但spyOnEvent()返回的是Stencil自定义的事件监听对象,不是Jest mock函数,所以会报类型错误。
  • E2E测试运行在独立的浏览器上下文,你在Node层定义的mockEvent无法传递到浏览器环境,模板里传focusEvent=${mockEvent}的写法完全无效。

修正后的测试代码

const page = await newE2EPage();
// 不需要传入无效的mock函数
await page.setContent(`<my-textbox></my-textbox>`);

await page.waitForSelector('input');
const inputEl = await page.find('input');
expect(inputEl).not.toBeNull();

// 1. 给组件本身绑定自定义事件监听,事件名和@Event中定义的eventName完全一致
const myTextbox = await page.find('my-textbox');
const focusSpy = myTextbox.spyOnEvent("focusEvent");

// 2. 触发input的focus动作
await inputEl.focus();
// 3. 等待Stencil处理完事件流、完成状态更新
await page.waitForChanges();

// 4. 使用Stencil专用的事件匹配器做断言
expect(focusSpy).toHaveReceivedEvent();
// 如果需要校验事件携带的参数可以用下面的写法
// expect(focusSpy).toHaveReceivedEventDetail(你预期的事件参数);

内容的提问来源于stack exchange,提问作者TimTheEnchanter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:57:03