代码之家  ›  专栏  ›  技术社区  ›  CaptainMorgan

toHaveBeenCalled角茉莉花试验

  •  2
  • CaptainMorgan  · 技术社区  · 7 年前

    我正在尝试为以下函数编写单元测试:

    onNextClick() {
        this.toast.clear();
    
        let checkedSubservices = new Array<number>();
        for (let i = 0; i < this.subSevices.length; i++) {
            if (this.subSevices[i].checked) {
                checkedSubservices.push(this.subSevices[i].id);
            }
        }
    
        if (checkedSubservices.length > 0)
        {
            this.bookService.setSubserviceIds(checkedSubservices);
            this.stepService.getNextStepByController(StepControllerNames.AllocationStepController)
                .then((ret: StepControllerReturnInfo) => {
                    this.goToControllerTarget(ret);
                }).catch((error) => {
                    // Error
                });
        }
        else
        {
            let options = { positionClass: 'toast-top-center', preventDuplicates: true };
            this.toast.error("Error.", "", options);
        }
    }
    

    我想测试一下 goToControllerTarget 已调用。因此,我创建了以下测试:

    it('onNextClick a service is checked', fakeAsync(() => {
        let ret = new ReturnInfo();
    
        let services = new Array<any>();
        services.push({id: 1, title: "Tite 1"});
        services.push({id: 2, title: "Tite 2"});
        services.push({id: 3, title: "Tite 3"});
    
        component.subSevices = services;
        const spy = spyOn(stepService, "getNextStepByController").and.returnValue(Promise.resolve(ret));
        const spy2 = spyOn(component, "goToControllerTarget");
    
        // Test Function
        component.onNextClick();
        tick(0);
    
        expect(spy2).toHaveBeenCalled();
    }));
    

    测试失败,因为 goToControllerTarget 函数未被调用。我已经进行了调试,并调用了catch代码路径,而不是then。

    2 回复  |  直到 7 年前
        1
  •  2
  •   AlexanderFSP    4 年前

    很好的一天!我想应该是这样的:

    expect(spy2.calls.any()).toBeTruthy();
    
        2
  •  0
  •   0x4a6f4672 pat    6 年前

    有时,角度测试无法调用某个服务函数,因为组件定义不正确。如果服务在角度组件中列为提供程序,而在中未定义 app.module.ts 那么测试可能会失败:

    @Component({
      selector: 'my-component',
      templateUrl: 'my-component.html',
      providers: [
        MyService,
     ]
    })
    

    在这种情况下,在测试中模拟服务不起作用。。

    it('should not work', async(inject([MyService], (myService) => {
      ..
      spyOn(myService, 'save').and.returnValue(Observable.of(someCalculation));
    

    ..我们必须将服务添加到 应用程序。单元ts 并将其从提供商列表中删除,以使其正常工作。