Per*_*oug 19 angularjs karma-runner
我们使用karma对我们的角度服务进行单元测试,这些服务包含$ http调用,因此我们有一个模拟的$ httpbackend,所以我们可以在没有server和db的情况下运行应用程序.这工作正常,服务可以调用$ http("someurl?id = 1234"),我们得到正确的数据.
但是当我们尝试在单元测试中做同样的事情时,我们无法让它工作,承诺永远不会解决,当它涉及$ http
服务:
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;
}
Run Code Online (Sandbox Code Playgroud)
模拟的$ httpbackend
$httpBackend
.whenGET(mocksUtills.urlRegex('/someurl'))
.respond(returnAllowedChildren); //returns a json object and httpstatus:200
Run Code Online (Sandbox Code Playgroud)
考试
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);
});
Run Code Online (Sandbox Code Playgroud)
但是收集是未定义的,.then()永远不会被调用.
尝试了很多东西以获得解决的承诺,$ rootScope.$ apply(),$ digest,$ httpBacke.flush(),但没有任何效果
因此,当应用程序中的控制器调用时,模拟的$ httpBackend可以正常工作,但是当在业力单元测试中直接调用服务时则不行
| 归档时间: |
|
| 查看次数: |
6573 次 |
| 最近记录: |