您好我想知道是否有人可以告诉我如何在角度和茉莉花2的模拟测试中测试回调结果。我们有一个调用只返回一些数据的服务,如下所示:
var getStuff = function (id) {
return $http.get("url/" + id)
.then(function (response) {
return response.data;
});
};
在我们的控制器中,我们在启动时调用此服务:
angular.module('controllers').controller("myController", ['$scope', 'service', function ($scope, service) {
var onGetStuff = function(data) {
//do something with the result here
}
$scope.getItems = function() {
service.getStuff(1).then(onGetStuff);
}
$scope.getItems();
}]);
我正在运行我的测试(稍后会发布代码,但是对onGetStuff的调用永远不会被调用,我似乎无法找出原因。这是测试代码:
//includes here
describe('Controller: Applicant Controller', function () {
var controller, $q, $scope, mockService, deferred, $rootScope;
beforeEach(module("controllers"));
beforeEach(function() {
mockService = {
getStuff: function (id) {
deferred = $q.defer();
deferred.resolve({somestuff: 1});
return deferred.promise;
}
};
spyOn(mockService, 'getStuff').and.callThrough();
});
beforeEach(inject(function ($rootScope, $controller, _$q_) {
$scope = $rootScope.$new();
$q = _$q_;
controller = $controller('myController', {
$scope: $scope,
service: mockService
});
}));
it("it should work", function () {
debugger;
});
});
如果我在chrome中单步执行调试器,则会调用模拟服务,但是" onGetStuff"我的控制器中的呼叫从未被呼叫,任何人都可以找出原因吗?
感谢 Mocksy。
答案 0 :(得分:1)
创建控制器后,您需要调用$rootScope.$apply()
才能运行任何then
回调。