angular - 如何测试这个函数的所有路径?
问题描述
我对单元测试几乎不熟悉,而且我被困在这个功能中。
onPreview(value: any): void {
this.showLoading('Cargando PDF...');
if (value) {
this._restService.getDocument(value).subscribe(
(restResult: any) => {
this._dialog.open(DialogPreviewDocument, {
data: restResult.data
});
},
error => {
Swal.fire({
icon: 'error',
title: 'Ocurrió un error al abrir este documento',
confirmButtonColor: '#3085d6',
confirmButtonText: 'Cerrar'
}).then(r => {
});
}
);
}
}
这是我的测试,第一个效果很好,但是当我从服务收到错误时尝试测试时,我收到了错误。
it('should call onPreview with error', (done => {
spyOn(component, 'onPreview');
let getDocument = spyOn(service, 'getDocument')
spyOn(Swal, 'fire')
component.onPreview("1614210817503");
setTimeout(() =>{
getDocument.and.throwError("Error")
expect(service.getDocument).toHaveBeenCalled();
expect(Swal.fire).toHaveBeenCalled()
})
}));
Error: Expected spy getDocument to have been called.
at <Jasmine>
at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:468:41
at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)
Error: Expected spy fire to have been called.
at <Jasmine>
at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:469:31
at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)
如果有人可以举例说明我做错了什么,我将不胜感激。提前致谢
解决方案
这里的主要问题是您需要知道什么是spyOn
做什么以及您实际上要测试什么。
spyOn()
用 stub 替换 spied 方法,这意味着它实际上并没有调用真正的方法。
所以在你的情况下,component.onPreview("1614210817503");
不是调用真正的方法,因为它被替换为存根spyOn(component, 'onPreview');
为了spyOn()
真正调用真正的方法,我们将它与.and.callThrough();
所以在这种情况下spyOn(component, 'onPreview').and.callThrough();
但是你甚至不必在onPreview
这里监视方法,你只需要调用真正的方法,然后存根内部调用的函数以获得所需的流程(例如使用spyOn().and.returnValue()
or spyOn().and.callFake()
)
推荐阅读
- node.js - vs code powershell 是这样说的
- swift - 当 self 被释放时,Unowned self 不会导致运行时中断?
- node.js - mp3 音频文件流媒体服务器
- jinja2 - dbt 宏可以接受其他宏作为参数吗?
- sql - 如何以更好的方式在表值函数的多个列中搜索字符串?
- python - 如何使用 python 将字符串转换为 DatetimeWithNanoseconds 格式?
- javascript - 阿波罗服务器 SQLDataSource VS 数据源
- dart - 如何在 Flutter 中让一个长的异步进程在屏幕上通知其进度
- azure - 如何调用 PullRequestQuery Azure Git API?
- python - s=s+c 字符串 concat 优化是如何决定的?