raju
raju

Reputation: 6936

Check if a function has been called, Angular unit testing

I have called a function inside ngOnInit,

ngOnInit() {
 this.isSubscribable();
}

I wan to do unit testing for this ngOnInit like this:

    it('Check isSubscribable is called from ngOnInit', async(async() => {
      spyOn(component, 'isSubscribable').and.callThrough();
      fixture.detectChanges();
      await fixture.whenStable();
      expect(component.isSubscribable).toHaveBeenCalled();

    }))

This is not working. I need some help on this.

Upvotes: 4

Views: 6851

Answers (2)

Maciej Manista
Maciej Manista

Reputation: 178

it('Check isSubscribable is called from ngOnInit', () => {
  const spy = spyOn(component, 'isSubscribable').and.callThrough();
  fixture.detectChanges();
  expect(spy).toHaveBeenCalled();
}))

You only need to manually call fixture.detectChanges() if your component has changeDetection set to ChangeDetectionStrategy.OnPush.

The above should work assuming that you have instantiated the component properly before the it assertion kicks in, like:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
  fixture = TestBed.createComponent(MyComponent);
  component = fixture.componentInstance;
})

If your code is that simple that you have only this method call in ngOnInit() then you might not need to use any async/await and .whenStable magic.

Upvotes: 2

Emilien
Emilien

Reputation: 2761

What if you try like this ?

it('Check isSubscribable is called from ngOnInit', () => {
  const spySubscribable = spyOn(component, 'isSubscribable');
  component.ngOnInit();
  expect(spySubscribable).toHaveBeenCalled();
});

Upvotes: 6

Related Questions