最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Angular - Unit testing keypress - Stack Overflow

matteradmin3PV0评论

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.

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.

ponent.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

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

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.

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.

ponent.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

it('should autofocus on cancel button on init', () => {
    spyOn(ponent, 'onDeny');
    ponent.keyEvent(ESCAPE);
    expect(ponent.onDeny).toHaveBeenCalled();
  });
Share asked Aug 30, 2018 at 11:02 physicsboyphysicsboy 6,37822 gold badges77 silver badges139 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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):

it('should log event and call self.onDeny() when keyEvent', () => {
  const spy1 = spyOn(ponent, 'onDeny');
  const spy2 = spyOn(console, 'log');
  const eventMock = {code: 'Escape'};
  ponent.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.ponent.html',
  styleUrls: ['./nav-header.ponent.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(ponent.toggleMenu, 'emit');
   spyOn(ponent.hamburgerRef.nativeElement, 'contains').and.returnValue(true);
   ponent.handleKeyboardEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
   expect(ponent.toggleMenu.emit).toHaveBeenCalled();
 });
Post a comment

comment list (0)

  1. No comments so far