代码之家  ›  专栏  ›  技术社区  ›  Sam

角度如何测试@HostListener

  •  7
  • Sam  · 技术社区  · 8 年前

    我有以下指示。当应用于输入元素时,它会检查字符,并在禁止字符时调用preventDefault:

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

    工作正常,但我不知道如何测试它。到目前为止,我有以下几点:

    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 { }
    });
    

    但它不起作用。不会触发按键事件。知道如何测试这个指令吗?

    1 回复  |  直到 8 年前
        1
  •  14
  •   Matias de Andrea Sam    5 年前

    我找到了解决办法。我只检查事件的defaultPrevented属性,而不是检查值(它永远不会更改)。

    我还遗漏了两件事:

    • 固定装置detectChanges();在beforeach中

    • 事件应可取消

    以下是完整测试:

         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 { }
        });
    
    推荐文章