【发布时间】:2013-06-29 11:14:40
【问题描述】:
我们使用 karma 对我们的 Angular 服务进行单元测试,这些服务包含 $http 调用,因此我们有一个模拟的 $httpbackend,因此我们可以在没有服务器和数据库的情况下运行应用程序。 这工作正常,服务可以调用 $http("someurl?id=1234") 并且我们得到正确的数据。
但是当我们尝试在单元测试中做同样的事情时,我们无法让它工作,当涉及到 $http 时,promise 永远不会解决
服务:
getAllowedTypes: function (contentId) {
var deferred = $q.defer();
$http.get(getChildContentTypesUrl(contentId))
.success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject('Failed to retreive data for content id ' + contentId);
});
return deferred.promise;
}
模拟的 $httpbackend
$httpBackend
.whenGET(mocksUtills.urlRegex('/someurl'))
.respond(returnAllowedChildren); //returns a json object and httpstatus:200
测试
it('should return a allowed content type collection given a document id', function(){
var collection;
contentTypeResource.getAllowedTypes(1234).then(function(result){
collection = result;
});
$rootScope.$digest();
expect(collection.length).toBe(3);
});
但是集合是未定义的,.then() 永远不会被调用。
尝试了几乎所有方法来解决承诺,$rootScope.$apply()、$digest、$httpBacke.flush(),但没有任何效果
所以模拟 $httpBackend 在应用程序中从控制器调用时有效,但在 karma 单元测试中直接调用服务时无效
【问题讨论】: