如何使用jasmine-karma测试angularjs服务中的函数

时间:2015-03-30 09:30:50

标签: angularjs karma-jasmine

我是karma-jasmine测试的新手。我编写了一个服务,使http调用api并返回数据对象。

app.service('service_name',['$http',function($http){
    this.getData=function(urlPath){
        var Data = $http.get(path).success(function(data){
                var getData = data;
                console.log("getData success");
                return getData;
            }).error(function(response){
                var getData = response;
                console.log("getData error");
                return getData;
            });

        console.log(Data);
        return Data;
    };
}]);

从控制器我将url传递给此服务函数并使用.then()回调获取数据;

service_name.getData(url).then(function(data){
    console.log('expected data: ', data);
});

1 个答案:

答案 0 :(得分:1)

我是这样做的:

首先,根据此article

设置测试环境

然后在测试规范中,使用以下测试模板测试您的服务功能,感谢Ben Lesh的出色blog

'use strict';

describe('service_name', function() {
  var service_name,
    httpBackend,
    resource;

  beforeEach(function() {
    module('yourAppName');

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service in order to avoid a name conflict.
    inject(function($injector, _service_name_) {
      service_name = _service_name_;
      httpBackend = $injector.get('$httpBackend');
    });
  });

  // make sure no expectations were missed in your tests.
  // (e.g. expectGET or expectPOST)
  afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });

  it('should have a getData function', function() {
    expect(angular.isFunction(service_name.getData)).toBe(true);
  });

  it('getData function should return data object if http request is successful', function() {
    var expectedData = data;
    httpBackend.expectGET('urlPath')
      .respond(expectedData);

    var actualResult;
    service_name.getData().then(function(response) {
      actualResult = response;
    });

    httpBackend.flush();

    expect(actualResult).toEqual(expectedData);
  });

  it('getData should return error message when http request is unsuccessful', function() {
    httpBackend.expectGET('urlPath').respond(500);

    var promise = service_name.getData('urlPath'),
      result = null;

    promise.then(function(foo) {
      result = foo;
    }, function(reason) {
      result = reason;
    });
    httpBackend.flush();
    expect(result).toBe("getData error");
  });

});

希望这有帮助。