检查函数是否被调用的单元测试用例

Unit test case to check if function is called

我正在尝试编写一个单元测试用例来检查函数是否在 switch case 中被调用 我有以下功能

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

      case 'temp':
        break;
    }
  }

并尝试编写与下面相同的单元测试用例,但测试用例总是失败'Expected spy toggleNext to have been called.'可能有什么问题任何指导将不胜感激。

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

先声明间谍,然后再调用函数

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