'Angular test case to test keyup event

Below mentioned code is working fine. which basically merge two events, merge them and do some operation on an input field. The problem is, I am not able to mock or write test cases for this code. Can anyone help me with this? I am using angular 12.

<input #myname value="John Doe">


ngAfterViewInit() {
const scrollEvents$ = fromEvent(this.input.nativeElement, 'blur');
const keyEvents$ = fromEvent(this.input.nativeElement, 'keyup').pipe(
  filter((e: KeyboardEvent) => e.keyCode === 13)
);
    
const allEvents$ = merge(scrollEvents$, keyEvents$);
allEvents$
  .pipe(
    takeUntil(this.unsubscribe$),
    map((evt: any) => evt.target.value),
    distinctUntilChanged()
  )
  .subscribe((text: string) => {
     this.data = text;
  });

}

Stackblitz link



Solution 1:[1]

You'll have a much easier time writing tests if you use event binding, like this. Then you can write unit tests against the method, and/or E2E tests against the whole interaction.

Solution 2:[2]

What I tend to do in general is to create "light" components and "fat" services.

In this case, this would mean to isolate the pipe logic into a service which is then passed via dependency injection into the component, something like this

export class AppService {
  constructor() {}

  allEvents(
    scrollEvents$: Observable<any>,
    keyEvents$: Observable<any>,
    unsubscribe$: Observable<any>
  ) {
    return merge(scrollEvents$, keyEvents$).pipe(
      takeUntil(unsubscribe$),
      map((evt: any) => {
        return evt.target.value;
      }),
      distinctUntilChanged()
    );
  }
}


  ngAfterViewInit() {
    const scrollEvents$ = fromEvent(this.input.nativeElement, 'blur');
    const keyEvents$ = fromEvent(this.input.nativeElement, 'keyup').pipe(
      filter((e: KeyboardEvent) => e.keyCode === 13)
    );
    // creating other input observables...

    const allEvents$ = merge(scrollEvents$, keyEvents$);
    allEvents$
      .pipe(
        takeUntil(this.unsubscribe$),
        map((evt: any) => evt.target.value),
        distinctUntilChanged()
      )
      .subscribe((text: string) => {
        console.log(text);
      });
  }

Now you can more easily test the service MyService which is where most of the logic resides.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jason Verber
Solution 2 Picci