Jasmine 仅当内部方法是 Function 的实例时才测试方法是否调用另一个方法
Jasmine test if method call another method only if the inner method is instance of Function
我需要使用 jasmine@2.99.1 测试该代码
我的代码-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 的实例,则不会被调用。
提前致谢
这种情况无解,因为你没有要测试的功能。然而,这可能对您有用...
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`
我需要使用 jasmine@2.99.1 测试该代码
我的代码-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 的实例,则不会被调用。
提前致谢
这种情况无解,因为你没有要测试的功能。然而,这可能对您有用...
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`