Unit tests for Pipe tap() in Angular

Asked

Viewed 124 times

3

I would like to test tap() inside my Pipe to cover this code snippet, just missing it so that I reach 100% test coverage.

fromEvent(this.input.nativeElement, 'keyup')
      .pipe(
        debounceTime(150),
        distinctUntilChanged(),
        **tap(() => {
          if (this.input.nativeElement.value.length > 2 || this.input.nativeElement.value.length == 0) {
            this.paginator.pageIndex = 0;
            this.loadAdmissionPage();
          }
        })**
      )
      .subscribe();
    this.paginator.page
      .pipe(
        **tap(() => this.loadAdmissionPage())**
      )
      .subscribe();

I tried in many ways to test but was unsuccessful.

  • 1

    Put the unitary test you tried

2 answers

1


normally tap tests itself just by giving a subscribe on the observable.

but as in your case is an event is a little more complicated.

I would do so:

const spy = jest.spyOn(SeuComponent, 'loadAdmissionPage');
const input = fixture.debugElement.query(
        By.css('algum filtro pra pegar esse seu this .input'),
 );
input.nativeElement.value='testing'
input.dispatchEvent(
  new KeyboardEvent('keyup', { key: 'y' })
);
expect(spy).toHaveBeenCalled();

// to test the second is easier

const spy = jest.spyOn(SeuComponent, 'loadAdmissionPage');
component.paginator=of({})

funcaoQueEnglobaEsseSeuCodigo();

component.paginator.next({})
expect(spy).toHaveBeenCalled();

0

I managed to run tests on top of TAP with the following code snippet.

it('it should verify the nativeElement keyup if length = 0', ()=>{
    component.input.nativeElement.value = '';
    component.input.nativeElement.dispatchEvent(new Event('keyup'));
});

it('it should verify the nativeElement keyup if length = 1', ()=>{
        component.input.nativeElement.value = 'a';
        component.input.nativeElement.dispatchEvent(new Event('keyup'));
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.