Angular - 单元测试按键

phy*_*boy 4 javascript testing karma-runner angular

我有一个检测按键的功能,如果按键按下 = 转义,则会触发一个功能。

我在伪造要传入的 KeyboardEvent 本身时遇到了麻烦。

我看到了这篇文章,但是实现这个解决方案会产生以下输出(我控制台记录了事件本身):

日志:KeyboardEvent{isTrusted:false} Chrome 68.0.3440 (Mac OS X 10.13.6) 当按下 ESCAPE 按钮时,ConfirmationComponent 应该调用 onDeny FAILED 预期的 spy onDeny 已被调用。

组件.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
  }
Run Code Online (Sandbox Code Playgroud)

测试文件

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

小智 5

不要费心实现键盘事件:它在每个浏览器上都会发生变化,通常甚至不起作用。

相反,测试您的函数本身(将 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);
});
Run Code Online (Sandbox Code Playgroud)