我在测试我的承诺单元测试时遇到了问题。
我提出了一个名为" expect(scope.test).toBe(12); "的断言。 这是在我的代码中返回的承诺内部。
以下是我尝试测试的实际代码:
$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);
}));
});
});
答案 0 :(得分:1)
在测试中调用$rootScope.$apply()
后,您似乎错过了对scope.getBudgets()
的调用。在Angular中,promise成功和错误回调作为摘要周期的一部分运行,必须通过测试手动触发。