Swarup
Swarup

Reputation: 57

Unit test case to check if function is called

I'm trying to write a unit test case to check if the function is being called inside the switch case I have a following function

public onMessageReceived(event) {
    switch (event && event['event']) {
      case 'onOptionSelected':
        this.toggleNext();
        break;

      case 'temp':
        break;
    }
  }

and have tried to write the unit test case for the same as below ,but the test case always fails 'Expected spy toggleNext to have been called.' what could be issue any guidance would be appreciated.

 it('should call toggleNext on onOptionSelected event', () => {
    component.onMessageReceived({ event: 'OptionSelected' });
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(spyOn<any>(component, 'toggleNext')).toHaveBeenCalled();
    });
  });

Upvotes: 1

Views: 1947

Answers (1)

PMO1948
PMO1948

Reputation: 2554

Declare the spy first, before you call the function

 it('should call toggleNext on onOptionSelected event', () => {
    const toggleSpy = spyOn(component, 'toggleNext');
    component.onMessageReceived({ event: 'onOptionSelected' });
    expect(toggleSpy).toHaveBeenCalled()
  });

Upvotes: 2

Related Questions