如何使用 jasmine-karma 测试 angularjs 服务内部的功能

How to test functions inside angularjs services using jasmine-karma

我是 karma-jasmine 的新手 testing.I 编写了一项服务,它使 http get 调用 api 和 returns 数据对象。

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);
});

我是这样做的:

首先,按照这个搭建测试环境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");
  });

});

希望对您有所帮助。