然后在内部调用Angular Jasmine测试函数

Aj1*_*Aj1 4 jasmine angularjs

这是我要测试的控制器功能.

  saveItem = (): void => {
    this.updateItem();
    this.loadingDialogService.showIndicator("Saving Item");        
this._editItemService.updateItem(this.item).then((updatedItem: Item) => {
            this.loadingDialogService.cancelDialog();
            this.goToMainView();
        }).catch(() => {
            this.loadingDialogService.showErrorDialog("Failed to Save Item");
            //this._log.error("Error CallingItemService");
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

it("should call method saveItem", () => {
            spyOn(controller, 'updateItem');
            spyOn(loadingDialogService, 'showIndicator');
            spyOn(editItemService, 'updateItem').and.callFake(() => {
                let result: Item
                deferred.resolve(result);  
                return deferred.promise;              
            });
            spyOn(loadingDialogService, 'cancelDialog');
            spyOn(controller, 'goToMainView');
            controller.saveItem();
            expect(controller.updateItem).toHaveBeenCalled();
            expect(loadingDialogService.showIndicator).toHaveBeenCalled();
            expect(_editItemService.updateItem).toHaveBeenCalled();
            expect(loadingDialogService.cancelDialog).toHaveBeenCalled();
            expect(controller.goToMainView).toHaveBeenCalled();
        });
Run Code Online (Sandbox Code Playgroud)

测试在最后两次预期失败,抛出错误说

预计间谍cancelDialog已被调用.

已被调用的间谍goToMainView被调用.

我想测试不执行内部功能功能.有人可以指出错误在哪里吗?

MBi*_*ski 5

您有解决的承诺,因此您需要在函数调用之后但在测试之前运行摘要循环.

it("should call method saveItem", () => {
        spyOn(controller, 'updateItem');
        spyOn(loadingDialogService, 'showIndicator');
        spyOn(editItemService, 'updateItem').and.callFake(() => {
            let result: Item
            deferred.resolve(result);  
            return deferred.promise;              
        });
        spyOn(loadingDialogService, 'cancelDialog');
        spyOn(controller, 'goToMainView');
        controller.saveItem();
        $scope.$digest();
        expect(controller.updateItem).toHaveBeenCalled();
        expect(loadingDialogService.showIndicator).toHaveBeenCalled();
        expect(_editItemService.updateItem).toHaveBeenCalled();
        expect(loadingDialogService.cancelDialog).toHaveBeenCalled();
        expect(controller.goToMainView).toHaveBeenCalled();
    });
Run Code Online (Sandbox Code Playgroud)

话虽如此,你的测试后来会引发你的问题,因为它有5个断言(expect()s).当一个人失败时,你将不得不浪费时间搞清楚它是哪一个.坚持每次测试一次断言(OAPT.)这应该是5次测试,每次都有一个断言.这样,当某些事情失败时,你就会知道它是什么.