angular 中的单元测试按键事件指令

Unit test Keypress event directive in angular

我有一个阻止用户输入字母的指令。对于我计划执行的单元测试,我将触发一个按键事件,如果它的编号将出现在文本框中,否则它不应该出现。当我 运行 测试时,事件和字符代码匹配并且函数返回 true 但我无法在文本框中看到值。

指令

  @HostListener('keypress', ['$event']) onKeyPress(event: any) {
    let enteredChar: number;
    enteredChar = parseInt(event.charCode, 10);
    return enteredChar >= 47 && enteredChar <= 57;
  }

单元测试

@Component({
  template: `
    <input PreventSpecialCharacters id="testComp" type="text" />
  `
})
class TestSpecialCharComponent {
  constructor(private el: ElementRef) {}
}

fdescribe('PreventSpecialCharactersDirective', () => {
  let fixture: ComponentFixture<TestSpecialCharComponent>;
  let inputEl: HTMLInputElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestSpecialCharComponent,
        PreventSpecialCharactersDirective
      ]
    });
    fixture = TestBed.createComponent(TestSpecialCharComponent);
    inputEl = fixture.nativeElement.querySelector('#testComp');
  });

  fit('should allow the input', () => {
    fixture.detectChanges();
    inputEl.dispatchEvent(makeKeyPressEvent('Digit1', 49, 49));
    expect(inputEl.value).toEqual('1');
  });

我必须创建一个自定义点击事件并将其直接传递给需要测试的函数。

  function makeKeyPressEvent(
    keyName: string,
    keyCode: number,
    charCode: number
  ) {
    const event = new KeyboardEvent('keypress');
    Object.defineProperties(event, {
      charCode: { value: charCode },
      keyCode: { value: keyCode },
      keyIdentifier: { value: keyName },
      which: { value: keyCode }
    });
    return event;
  }

测试如下

   const directive = new PreventSpecialCharactersDirective();
    const result = directive.onKeyPress(makeKeyPressEvent('Digit1', 49, 49));
    expect(result).toBeTruthy();