Angular testing .next on ngOnInit

Viewed 56

have this function .next I have to make ONE unit test for:

enter image description here

I can't make that red part on imgur work .This is what I tried:

describe('ngOnInit', async () => {
 beforeEach(() => {
   (component as any).getTextTemplates = jasmine.createSpy();
   component.msgBusService.register = jasmine.createSpy();
 });

 it('should getTextTemplates with searchParam', () => {
  const searchParam = 'param';
  component.ngOnInit();
  component.getTextTemplates(searchParam);
  expect(component.getTextTemplates).toHaveBeenCalledWith(searchParam);
});
});

Info: The getTextTemplates function has string as optional parameter: getTextTemplates(search?: string); Any ideas? Should I create .next somehow? Thanks.

1 Answers

You can use a combination of fakeAsync and flush to ensure the observables are completed before validating, also you can just mock the observables and subjects with the rxjs of() operator!

app.com.ts

import { Component } from '@angular/core';
import { BehaviorSubject, debounceTime, takeUntil } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'test';
  searchInputSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  destroyedSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  debounceDuration = 1000;
  searchParam = 'test';
  
  ngOnInit() {
    this.getTextTemplates();
    this.searchInputSubject.pipe(
        takeUntil(this.destroyedSubject),
        debounceTime(this.debounceDuration),
    ).subscribe({
      next: () => {
        this.getTextTemplates(this.searchParam);
      }
    })

  }

  getTextTemplates(_: any = null) {}
}

app.com.spec.ts

import { fakeAsync, flush } from '@angular/core/testing';
import { of, Subject } from 'rxjs';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  let component: any;
  beforeEach(async () => {
    component = new AppComponent();
  });

  describe("ngOnInit", async () => {
    beforeEach(() => {
      spyOn<any>(component, 'getTextTemplates');
      component.searchInputSubject = of(true) as any;
      component.destroyedSubject = new Subject() as any;
    });
  
    it("should getTextTemplates with searchParam", fakeAsync(() => {
      component.ngOnInit();
      flush();
      expect(component.getTextTemplates).toHaveBeenCalledTimes(2);
    }));
  });
});

coverage on local

enter image description here

Related