首页 > 解决方案 > 如何测试这个函数的所有路径?

问题描述

我对单元测试几乎不熟悉,而且我被困在这个功能中。

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)

如果有人可以举例说明我做错了什么,我将不胜感激。提前致谢

标签: angularunit-testingjasminekarma-jasmine

解决方案


这里的主要问题是您需要知道什么是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()


推荐阅读