单元测试Keypress事件指令,以角度显示

时间:2020-07-22 09:19:02

标签: angular karma-jasmine angular-directive keyboard-events angular-unit-test

我有一条指令,禁止用户输入字母。对于单元测试,我计划执行该操作,以触发按键事件,如果事件编号在文本框中显示,否则将不存在。当我运行测试时,事件和字符代码匹配,并且该函数返回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');
  });

1 个答案:

答案 0 :(得分:0)

我必须创建一个自定义的click事件,并将其直接传递给需要测试的功能。

  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();