-1

I'm subscribing to a behavior subject in onInit and based on the result I'm calling a function. My code is like

subscription = new Subscription();
constructor(private myService: MyService) {}
ngOnInit() {
  this.subscription = this.myService.event.subscribe(response => {
    if(response){
       this.myFunction();
    }
  });
}
myFunction() {}

and I'm test this by trying like below

describe('AppComponent', () => {
  let event = new BehaviorSubject(false);
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ], imports: [

      ], providers: [{
        provide: MyService, useValue: {
          event: event
        }
      }]
    }).compileComponents();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should call myFunction', (done) => {
    const myService = fixture.debugElement.injector.get(MyService);
    myService.event.next(true);
    component.ngOnInit();
    const spy = spyOn(component, 'myFunction');
    myService.event.subscribe((event: boolean) => {
      expect(spy).toHaveBeenCalled();
      done();
    })
  });
});

and I'm getting my spy is not called. Please help me to fix my code. Thanks a lot.

e.k
  • 1,333
  • 1
  • 17
  • 36

1 Answers1

0

You're spying too late it seems.

Try the following:

// !! Spy first
const spy = spyOn(component, 'myFunction');
// !! Then call ngOnInit
component.ngOnInit();

Edit Try with fakeAsync and tick.

it('should call myFunction, fakeAsync(() => {
  const myService = fixture.debugElement.injector.get(MyService);
  myService.event.next(true);
  const spy = spyOn(component, 'myFunction');
  
  component.ngOnInit();
  
  tick();

  expect(spy).toHaveBeenCalled();
}));

The fakeAsync/tick should hopefully wait until the subscribe is done before moving on to the expect.

AliF50
  • 16,947
  • 1
  • 21
  • 37