AngularJS测试回调到服务中的函数

时间:2015-11-12 19:46:09

标签: angularjs jasmine promise angular-promise angular-services

我正在寻找一个执行传递给then函数的回调函数的Jasmine单元测试。这个函数被链接到一个对AngularJS $ http服务的调用,它在一个自定义服务中。这是我正在使用的代码:

app.service('myService', function($rootScope, $http) {
  var service = this;

  var url = 'http://api.example.com/api/v1/resources';

  service.resources = {
    current: []
  };

  service.insertResource = function (resource) {
    return $http.post(url, resource).then(function(response){
      $rootScope.$broadcast('resources:updated', service.resources.current);
      return response;
    });
  };
});

这是我尝试编写执行此回调的测试,但无济于事:

describe('resource service', function() {

  beforeEach(angular.mock.module('myapp'));

  var resourceService;

  beforeEach(inject(function(_resourceService_) {
    resourceService = _resourceService_;
  }));

  it('should insert resources', function() {
    resourceService.insertResource({});
  });
});

1 个答案:

答案 0 :(得分:0)

您可以采取以下几种方法:

  • 使用$ httpBackend.expectPOST
  • 使用$ httpBackend.whenPOST
  • 将回调中的代码移动到命名函数(不是匿名函数)并为此函数编写测试。我有时采用这条路线b / c我不想用$httpBackend编写测试的麻烦。我只测试回调函数,我不测试我的服务是否正在调用回调。如果你可以生活,那就是更简单的方法。

查看$httpBackend的文档以获取详细信息。这是一个简单的例子:

describe('resource service', function() {

  beforeEach(angular.mock.module('myapp'));

  var resourceService, $httpBackend;

  beforeEach(inject(function($injector) {
    resourceService = $injector.get('resourceService');
    $httpBackend = $injector.get('$httpBackend');
  }));

  afterEach(function() {
    // tests will fail if expected HTTP requests are not made
    $httpBackend.verifyNoOutstandingRequests();
    // tests will fail if any unexpected HTTP requests are made
    $httpBackened.verifyNoOutstandingExpectations();
  });

  it('should insert resources', function() {
    var data: { foo: 1 }; // whatever you are posting
    // make an assertion that you expect this POST to happen
    // the response can be an object or even a numeric HTTP status code (or both)
    $httpBackend.expectPOST('http://api.example.com/api/v1/resources', data).respond({});
    // trigger the POST
    resourceService.insertResource({});
    // This causes $httpBackend to trigger the success/failure callback
    // It's how you workaround the asynchronous nature of HTTP requests
    // in a synchronous way
    $httpBackend.flush(); 
    // now do something to confirm the resource was inserted by the callback
  });
});