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

如何在Angular/Spectator测试中模拟滚轮/滚动事件?

如何测试<input type="number">滚动修改值的行为

我编写了一个指令用于阻止特定输入框的滚动/滚轮事件,现在需要先验证原生<input type="number">字段在滚动时会修改其值,但目前卡在了这一步。

我已编写了对应的测试组件,代码如下:

@Component({
  selector: 'test-scroll-input',
  standalone: true,
  imports: [MatInputModule, ReactiveFormsModule],
  template: `
    <form [formGroup]="form" autocomplete="off">
      <mat-form-field>
        <mat-label>Værdi</mat-label>
        <input matInput type="number" formControlName="value" />
      </mat-form-field>
    </form>
  `,
})
class TestScrollInputComponent {
  public form = new FormGroup({
    value: new FormControl(1),
  });
}

beforeEach(() => {
  spectator = createComponent();
});

我的目标是编写测试用例,模拟输入框内的滚动操作,验证其值会从初始的1发生变化,伪代码示例如下:

it('should change the input from 1 to 2, when scrolling in the input field',()=>{
  inputElement = spectator.query('input[type="number"]');

  spectator.click(inputElement);
  // insert scroll event here

  expect(spectator.component.form.controls.value.value).toBe(2)
)};

解决方法

要实现这个测试,需要满足两个核心条件:确保输入框处于聚焦状态,以及正确触发包含方向参数的滚轮事件。完整的测试代码如下:

it('滚动输入框时数值应从1变为2', () => {
  const inputElement = spectator.query<HTMLInputElement>('input[type="number"]');
  
  // 聚焦输入框(原生行为要求输入框激活时滚动才会修改数值)
  inputElement.focus();
  
  // 模拟向上滚动:deltaY为负时,数值增加;deltaY为正时,数值减少
  inputElement.dispatchEvent(new WheelEvent('wheel', { deltaY: -100 }));
  
  expect(spectator.component.form.controls.value.value).toBe(2);
});

额外注意事项

  • deltaY的取值决定数值变化方向:负数值对应向上滚动,数值递增;正数值对应向下滚动,数值递减
  • 部分浏览器可能需要调整deltaY的绝对值(比如-50、-100),确保能触发数值变化
  • 测试原生行为时,要确保测试组件中没有引入你编写的阻止滚动指令,避免干扰原生逻辑;验证完原生行为后,再添加指令测试阻止效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 03:27:51