我在测试诺言单元测试时遇到问题。

我提出了一个名为“ expect(scope.test).toBe(12);”的断言。
这是在promise内部,然后在我的代码中返回。

以下是我要测试的实际代码:

$scope.getBudgets = function(){
    BudgetService.getBudgets().then(function(response) {
        $scope.test = 12;

    }, function(response) {

    });
}


以下是我的单元测试:

describe('budgetOverviewCtrl tests', function() {

beforeEach(module('app'));
beforeEach(module('ngRoute'));

var ctrl, scope, deferred;

describe('budgetOverviewCtrl with test', function() {
    beforeEach(inject(function($controller, _$rootScope_) {

        scope = _$rootScope_.$new();

        ctrl = $controller('budgetOverviewCtrl', {
            $scope: scope
        });
    }));

    it('Should check if getBudgets service promise exists and returns as expected', inject(function($injector, $q, BudgetService) {

        BudgetService = $injector.get("BudgetService");

        deferred = $q.defer();
        deferred.resolve({"Hello": "World"});

        spyOn(BudgetService, 'getBudgets').and.callFake(function() {
            return deferred.promise;
        });

        scope.getBudgets();

        expect(BudgetService.getBudgets).toHaveBeenCalled();

        **//Below line isnt called - this is inside the promise then.**
        expect(scope.test).toBe(12);
    }));
});
});

最佳答案

在测试中,在呼叫$rootScope.$apply()之后,您似乎错过了对scope.getBudgets()的呼叫。在Angular中,promise成功和错误回调是摘要循环的一部分,必须从测试中手动触发。

07-24 09:50
查看更多