如何在AngularJS中为$ http承诺创建单元测试

时间:2015-07-27 06:43:35

标签: javascript angularjs unit-testing karma-jasmine

我有一个带有函数的服务,可以使用$ http和promise。我想用茉莉花创建一个单元测试。

account.service('AccountService', ['$q', '$http', function ($q, $http) {
    this.getServerDataForUrl = function (url) {
         var def = $q.defer();
         $http.get(url)
              .success(function (data) {
                   if (data) {
                      def.resolve(data);
                   } else {
                      def.reject();
                   }
               })
               .error(function (error) {
                   if (data) {
                      def.resolve(data);
                   } else {
                      def.resolve();
                   }
                });
         return def.promise;
    };
}]);

更新:在回调时更改一些代码 我正在搜索它,但它没有给我这样的功能。有人给我一些例子来创建关于它的单元测试。我觉得这个功能很简单。感谢。

3 个答案:

答案 0 :(得分:3)

你应该真的只是

return $http.get(url);

在延迟对象中包装承诺毫无意义。

这是我能想到的唯一可测试的东西

describe('AccountService test', function() {
    var $http;

    beforeEach(module('accountModule', function($provide) {
        $provide.value('$http', $http = jasmine.createSpyObj('$http', ['get']));

        // if you aren't going to change the code to not wrap
        // the $http promise, add this

        var httpPromise = {
            success: function(cb) {
                cb('success');
                return httpPromise;
            },
            error: function(cb) {
                cb('error');
                return httpPromise;
            }
        };

        $http.get.and.returnValue(httpPromise);
    }));

    it('proxies through to $http.get', inject(AccountService) {
        AccountService.getServerDataForUrl('url');
        expect($http.get).toHaveBeenCalledWith('url');
    }));
});

答案 1 :(得分:1)

在spec中创建一个变量,它保存AccountService实例的引用,并使用角度注入函数来实例化它。

现在您可以使用jasmine spys来测试函数或使用游行者来测试服务公共成员。

    var AccountSvs = undefined;
    beforeEach(inject(function (AccountService) {
    AccountSvs = AccountService;
    }));

    it('..', function(){
      expect(AccountSvs.getServerDataForUrl).toBeDefined();
AccountSvs.getServerDataForUrl().then(/*success callback*/function(){}, /*error callback*/function(){}, /*notify callback*/function(){});
    });

答案 2 :(得分:0)

在单元测试中处理承诺并不是什么大问题,因为它需要以下异步。

describe('AccountService',function(){
 var service = null;
    beforeEach(inject(function (AccountService) {
    service = AccountService;
    }));

    it('checkService here', function(done){
         expect(service .getServerDataForUrl).toBeDefined();
        service .getServerDataForUrl().then(function(resp){
         expect(resp.data).not.ToBeNull();   
          done();

     });
});

resp.data将包含您从服务中返回的实际数据。