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

Angular:如何使用Jest测试DigitsOnly数字输入指令?

Angular DigitsOnly指令测试方案

我实现了一个DigitsOnly指令,用于限制输入框仅接受数字。现在需要验证该指令功能是否正常,使用Jest作为测试框架,也接受Jasmine的测试方案。之前尝试模拟按键或直接设置输入值都没成功。

指令代码

@Directive({
  selector: '[digitsOnly]'
})
export class DigitsOnlyDirective {

  constructor(private _el: ElementRef) {
  }

  @HostListener('input', ['$event']) onInputChange(event: any) {
    const initialValue = this._el.nativeElement.value;
    this._el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');

    if (initialValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

当前测试代码(已完善)

describe('DigitsOnlyDirective', () => {
  let debugElement: DebugElement;
  let fixture: ComponentFixture<TestComponent>;
  let inputElement: HTMLInputElement;

  @Component({
    selector: 'my-test-component',
    template: `
        <div>
            <input digitsOnly/>
        </div>`
  })
  class TestComponent {
  }

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [TestComponent, DigitsOnlyDirective]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    debugElement = fixture.debugElement.query(
      By.directive(DigitsOnlyDirective)
    );
    inputElement = debugElement.nativeElement;
  });

  it('should create the directive', () => {
    expect(fixture).toBeTruthy();
    expect(debugElement).toBeTruthy();
  });

  it('should retain only digits when mixed characters are entered', () => {
    inputElement.value = 'abc123def456';
    inputElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(inputElement.value).toBe('123456');
  });

  it('should keep pure digit input unchanged', () => {
    inputElement.value = '987654';
    inputElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(inputElement.value).toBe('987654');
  });

  it('should clear value when only non-digit characters are entered', () => {
    inputElement.value = '!@#$%^&*()';
    inputElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(inputElement.value).toBe('');
  });
});

关键测试说明

  • 指令监听的是input事件,直接修改输入框value不会触发指令逻辑,必须手动调用dispatchEvent(new Event('input'))触发事件
  • 触发事件后需要调用fixture.detectChanges()同步Angular的变更检测,确保视图和数据同步
  • 覆盖混合字符、纯数字、纯非数字三种核心场景,验证指令逻辑的完整性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:05:38