Angular如何测试@HostListener [英] Angular How to test @HostListener

查看:245
本文介绍了Angular如何测试@HostListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下指令.应用于输入元素时,它将检查字符并在禁止字符时调用preventDefault:

I have the following directive. When applied to an input element, it checks for characters and calls preventDefault when the character is forbidden:

@Directive({
 selector: '[cdtPreventInput]'
})
  export class PreventInputDirective implements OnInit {

  // the list of characters that are to be prevented
  @Input() cdtPreventInput: String;

  constructor() { }

  ngOnInit() {
    if (!this.cdtPreventInput) {
      throw new Error('cdtPreventInput cannot be used without providing a 
          list of characters.');
    }
  }

 @HostListener('keypress', ['$event']) onKeyPress(event) {
   if (_.includes(this.cdtPreventInput.split(','), event.key)) {
    event.preventDefault();
  }
}

工作正常,但我不知道如何进行测试.到目前为止,我有以下内容:

Works fine, but I can't figure out how to test it. I have the following so far:

describe('PreventInputDirective', () => {
  let fixture;
  let input: DebugElement;

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [PreventInputDirective, TestComponent]
    }).createComponent(TestComponent);

    input = fixture.debugElement.query(By.directive(PreventInputDirective));
  });

  it('should create an instance', () => {
    const directive = new PreventInputDirective();
    expect(directive).toBeTruthy();
  });

 it('should prevent default keypress event', () => {
    const event = new KeyboardEvent('keypress', {
      'key': '.'
    });
     input.nativeElement.dispatchEvent(event);

     expect(input.nativeElement.value).toEqual('');
  });

  @Component({
    template: `<input cdtPreventInput="." />`
  })
  class TestComponent { }
});

虽然没有用.按键事件未触发.知道如何测试该指令吗?

It's not working though. The keypress event is not triggered. Any idea how to test this directive ?

推荐答案

我找到了解决方案.不用检查值(永远不变),而只需检查事件的defaultPrevented属性.

I found a solution. Instead of checking for value (which never changes), I just check the defaultPrevented property on the event.

我还错过了两件事:

  • fixture.detectChanges();在beforeEach

  • fixture.detectChanges(); in the beforeEach

事件应该可以取消

这是完整的测试:

 describe('PreventInputDirective', () => {
  let fixture;
  let input: DebugElement;

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [PreventInputDirective, TestComponent]
    }).createComponent(TestComponent);

    input = fixture.debugElement.query(By.directive(PreventInputDirective));
    fixture.detectChanges();
  });

  it('should create an instance', () => {
    const directive = new PreventInputDirective();
    expect(directive).toBeTruthy();
  });

  it('should prevent keypress event', () => {
    const event = new KeyboardEvent('keypress', {
      'key': '.',
      cancelable: true
    });

    input.nativeElement.dispatchEvent(event);
    expect(event.defaultPrevented).toBeTruthy();
  });

  it('should not prevent keypress event', () => {
    const event = new KeyboardEvent('keypress', {
      'key': '5',
      cancelable: true
    });

    input.nativeElement.dispatchEvent(event);
    expect(event.defaultPrevented).toBeFalsy();
  });

  @Component({
    template: `<input cdtPreventInput="." />`
  })
  class TestComponent { }
});

这篇关于Angular如何测试@HostListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆