简体   繁体   English

Angular - 单元测试按键

[英]Angular - Unit testing keypress

I have a function that detects a keypress and if the key pressed = escape, a function is fired.我有一个检测按键的功能,如果按下的键 = 转义,则会触发一个功能。

I am having trouble with faking the KeyboardEvent itself to be passed in.我在伪造要传入的 KeyboardEvent 本身时遇到了麻烦。

I saw this post , but implementing this solution yields the following output (I console.logged the event itself):我看到了这篇文章,但实施此解决方案会产生以下输出(我控制台记录了事件本身):

LOG: KeyboardEvent{isTrusted: false} Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent should call onDeny when ESCAPE button pressed FAILED Expected spy onDeny to have been called.日志:KeyboardEvent{isTrusted: false} Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent 应该在按下 ESCAPE 按钮时调用 onDeny FAILED 预期间谍 onDeny 已被调用。

component.ts组件.ts

@HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    console.log(event);
    // Press escape - close dialog with simulated 'cancel' click
    if (event.code === 'Escape') {
      this.onDeny();
    }
  }

  onDeny() {
     // something is done here
  }

test.ts测试.ts

it('should autofocus on cancel button on init', () => {
    spyOn(component, 'onDeny');
    component.keyEvent(ESCAPE);
    expect(component.onDeny).toHaveBeenCalled();
  });

Don't bother implementing a keyboard event: it changes on every browser and usually doesn't even work.不要费心实现键盘事件:它在每个浏览器上都会发生变化,而且通常甚至不起作用。

Instead, test your function itself (leave Angular testing behavior to Angular itself):相反,测试你的函数本身(将 Angular 测试行为留给 Angular 本身):

it('should log event and call self.onDeny() when keyEvent', () => {
  const spy1 = spyOn(component, 'onDeny');
  const spy2 = spyOn(console, 'log');
  const eventMock = {code: 'Escape'};
  component.keyEvent(eventMock);
  expect(spy1).toHaveBeenCalledWith();
  expect(spy2).toHaveBeenCalledWith(eventMock);
});

Try the following -尝试以下 -

import { Component, OnInit, Input, EventEmitter, Output, HostListener, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-nav-header',
  templateUrl: './nav-header.component.html',
  styleUrls: ['./nav-header.component.scss']
})
export class NavHeaderComponent implements OnInit {
  @ViewChild('ham')
  hamburgerRef: ElementRef;

  @Output()
  toggleMenu: EventEmitter<void>;

  constructor() {
    this.toggleMenu = new EventEmitter<void>();
  }

  ngOnInit() {}

  emitToggle() {
    this.toggleMenu.emit();
  }

  @HostListener('keydown', ['$event'])
  public handleKeyboardEvent(event: any): void {
    event.stopPropagation();
    switch (event.key) {
      case 'Enter': {
        if (this.hamburgerRef.nativeElement.contains(event.target)) {
          this.emitToggle();
        }
        break;
      }
      case 'Tab': {
        break;
      }
    }
  }
}


 it('it should user emit toogle', () => {
   spyOn(component.toggleMenu, 'emit');
   spyOn(component.hamburgerRef.nativeElement, 'contains').and.returnValue(true);
   component.handleKeyboardEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
   expect(component.toggleMenu.emit).toHaveBeenCalled();
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM