使用 Karma 和 Jasmine 测试 AngularJS 服务(工厂)

Testing AngularJS Service (Factory) with Karma and Jasmine

我的服务(工厂)是这样的:

angular.module('App')
  .factory('SalesService', function($http) {
    return {
      getSales: function(data) {
        return $http.get('/sales');
      }
  }
})

我收到 意外请求:GET /sales 当我这样做时:

describe('Sales Services', function() {

  beforeEach(module('App'));

  it('should get the sales data', inject(function(SalesServices, $httpBackend) {
    SalesServices.getSales().then(function(data) {
        expect(data.success).toBeTruthy();
    });
    $httpBackend.flush();
  }));

});

我觉得一切都很好。我做错了什么?

为了不inject你的依赖在所有测试中,你应该使用beforeEach:

var $httpBackend, SalesService;

beforeEach(module('App'));

beforeEach(inject(function (_$httpBackend_, _SalesService_) {
  $httpBackend = _$httpBackend_;
  SalesService = _SalesService_;
}));

然后,在你的测试中你应该期望调用一些URL:

it('should get the sales data', function () {
  // given
  var response = { data: 'result' };
  var result = {}
  $httpBackend.expect('GET', '/sales').respond(200, response);

  // when
  SalesService.getSales().then(function (responseData) {
    result = responseData;
  });
  $httpBackend.flush();

  // then
  expect(result).toEqual(response);
});

最后您需要确保没有待处理的请求:

afterEach(function () {
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});