angular - 茉莉花测试失败 - 但日志表明并非如此
问题描述
此测试引发错误Expected spy phone to have been called.
- 正在调用模拟类方法,如log
终端中所示。模拟类没有被任何其他测试调用。我假设我在这里遗漏了一些简单的东西,但我不确定为什么formatSpy
测试失败了。
我在 TestBed.ConfigureTestingModule 中的提供者:
{provide: FormatService, useClass: FormatServiceMock},
我的模拟课:
export class FormatServiceMock {
phone() {
console.log('format phone');
return;
}
}
我的功能正在测试:
public getPhone(): string {
if (this.data && this.data.settings) {
return this.format.phone(this.data.settings.phone);
} else {
return '';
}
}
我的测试:
it('should call format service', () => {
service.data = data;
service.getPhone();
let formatSpy = spyOn(format, 'phone').and.callThrough();
expect(formatSpy).toHaveBeenCalled();
});
我的输出:
LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6): Executed 28 of 87 SUCCESS (0 secs / 1.477 secs)
LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6) EnvironmentService getPhone should call format service FAILED
Expected spy phone to have been called.
更新 将 MOCK 更改为:
export class FormatServiceMock {
phone(phone) {
return phone;
}
}
并测试:
it('should call format service', () => {
service.data = data;
let result = service.getPhone();
let formatSpy = spyOn(format, 'phone').and.callThrough();
expect(result).toEqual('5553335555'); //<--- PASSES
expect(formatSpy).toHaveBeenCalled(); // <---- FAILS
})
随着我的破解,我可以删除expect(formatSpy).toHaveBeenCalled()
并知道该功能按预期工作 - 但对我来说仍然是一个谜,为什么我的间谍在一切都按预期执行时失败了。
解决方案
在您的代码调用被监视函数之前,需要调用您的 spyOn函数
这应该解决它:
let formatSpy = spyOn(format, 'phone').and.callThrough();
service.getPhone();
expect(formatSpy).toHaveBeenCalled();
推荐阅读
- php - INNER JOIN ,我不知道为什么我收到警告:mysqli_fetch_array() 期望参数 1 是 mysqli_result,bool 给出
- python - 可选参数 Python
- javascript - 无法分配给只读属性 ERROR
- reactjs - 如何在 d3 中的 tooltip.html() 中添加 React i18n 翻译标签
- css - 一些 CSS 字符代码(\25b6 和 \25c0)在 flexbox 中没有对齐
- c# - 如何将 json 数组转换为包含重复键的字典?
- google-apps-script - 如何减少在 for 循环中使用 setValues() 和 copyto() 的谷歌应用脚本的运行时间
- flutter - Dart 中的 ListMultimap 与 Multimap
- react-native - How to check if 3rd party library is installed in React Native
- azure - 通过 Azure 将 Dynamics 365 Sales 数据移动到本地应用程序?