javascript - 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 的实例,而不是调用。
提前致谢
解决方案
这种情况无法解决,因为您没有要测试的功能。但是,这可能对您有用...
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`
推荐阅读
- c# - 如何确定使用哪种方法,在 ASP.NET Core 中使用我的自定义属性
- php - 无法获取在 codeigniter 中给定时间之间存在的记录
- javascript - 子状态已更新但未呈现
- azure - Azure Devops kubectl 任务部署映像的状态为 ErrImagePull/ImagePullBackOff
- angular - Angular - cdkDrag 不适用于 span 标签
- django - 使用 Django 和 NextJS 进行用户身份验证
- git - 如何合并 git 存储库和其他一些本地存储文件?
- android - RangeError(索引):无效值:有效值范围为0
- reactjs - 当我打开第二次折叠时,状态正在获取相同的数据。我需要在触发崩溃时获取数据
- android - RecyclerView 中的 Fragment 位于 Fragment 中