首页 > 解决方案 > Jasmine 测试方法是否仅在内部方法是 Function 的实例时才调用另一个方法

问题描述

我需要使用 jasmine@2.99.1 测试该代码

来自 my-component.ts 的代码

startChatting(agent, platform) {
  if (this.params.startChatting instanceof Function) {
    this.params.startChatting(agent, platform, this.params.rowIndex);
  }
}

并且我尝试测试上面的代码:my-component.spec.ts

it('ensure that startChatting does not call "params.startChatting" if "params.startChatting" 
   is not instanceOf Function', () => {
     component.params = {
       startChatting: null,
       rowIndex: 2
     }

     spyOn(component.params, 'startChatting');
     component.startChatting('dummyId', 'telegram');

     expect(component.params.startChatting).not.toHaveBeenCalled();
});

但测试失败并显示此消息“错误:未调用预期的间谍 startChatting。” 这意味着调用了内部方法。

因此,我尝试控制台记录我设置为 null 的内部方法,正如您在测试用例开始时看到的那样,但我发现它不是 null 而是如下:

ƒ () { return fn.apply(this, arguments); }

我知道在调用 spyOn 函数后情况发生了变化。

所以我的问题是如何测试这种情况?我需要确保 params.startChatting 不是 Function 的实例,而不是调用。

提前致谢

标签: javascriptangularunit-testingjasminekarma-jasmine

解决方案


这种情况无法解决,因为您没有要测试的功能。但是,这可能对您有用...

let startChattingGetterInwoked = 0;
component.params = {
  get startChatting() {
    startChattingGetterInwoked++;
    return null;
  },
  rowIndex: 2
}

component.startChatting('dummyId', 'telegram');
expect(startChattingGetterInwoked).toBe(1);
// Not sure how offten it is called, but at least one should be called due to `typeof`


推荐阅读