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

如何在StencilJS单元测试中触发键盘事件验证输入格式化方法调用?

StencilJS 输入框格式化方法单元测试解决方案

你现有的测试逻辑只验证了自定义事件触发时的方法调用,没有覆盖真实用户键盘输入触发事件的场景,而且直接实例化组件的方式不会关联模板里的事件绑定逻辑,测试结果和实际运行场景不符。正确的实现方式如下:

第一步:使用Stencil官方测试工具newSpecPage渲染组件

Stencil 内置的newSpecPage会基于JSDOM模拟真实浏览器环境,完整渲染组件模板、绑定事件,是官方推荐的单元测试实现方式。

第二步:完整测试用例代码

import { newSpecPage } from '@stencil/core/testing';
import { MyComponent } from './my-component'; // 替换为你的组件实际路径

it('should trigger valueFormat and format input value correctly when user types number', async () => {
  // 1. 渲染组件
  const page = await newSpecPage({
    components: [MyComponent],
    html: `<my-component></my-component>`, // 替换为你的组件实际标签名
  });
  const comp = page.rootInstance;
  
  // 2. 监听valueFormat方法调用
  const formatSpy = jest.spyOn(comp, 'valueFormat');
  
  // 3. 拿到组件内的输入框DOM节点(替换为你组件里input对应的选择器,比如有class就用'.input-class',有ref可以用page.root.querySelector('[ref="myInput"]'))
  const inputEl = page.root.querySelector('input') as HTMLInputElement;
  
  // 4. 模拟用户输入:赋值+触发对应事件(根据你组件里绑定的事件调整,绑定的是onInput就触发input事件,绑定onKeyup就触发keyup事件)
  inputEl.value = '1234';
  await inputEl.dispatchEvent(new Event('input'));
  await page.waitForChanges();

  // 5. 断言验证
  expect(formatSpy).toHaveBeenCalled(); // 验证方法被调用
  expect(comp.value).toBe('1,234.00'); // 额外验证格式化结果符合预期,可选但推荐添加
});

说明

  • 如果你的输入框是封装的第三方组件,调整选择器到实际可触发输入事件的节点即可
  • 如果你只需要验证方法被调用,去掉格式化结果的断言即可,但推荐同时验证功能正确性,避免空方法也能通过测试的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:45:11