在服务中使用$ httpBackend进行测试

时间:2014-07-12 12:47:57

标签: angularjs unit-testing karma-runner karma-jasmine

我刚刚开始使用AngularJS进行一些测试,但我不能说我完全理解它。我想在我的工厂测试REST API方法,但我只是遇到错误。不知道我做错了什么。任何人都可以帮助我吗?

我的工厂:

'use strict';

angular.module('corsaneApp')
  .factory('resourceService', ['$http', '$log', '$resource', '$sce', 'listService', 'global', 'config',
    function($http, $log, $resource, $sce, listService, global, config) {

      var search = null;

      return {
        post: function(name, url, type, res) {
          var prefix = 'http';
          if (url.substr(0, prefix.length) !== prefix) {
            url = prefix + '://' + url;
            $log.info('NewUrl ' + url);
          }
          // Post resource
          $http.post(config.apiBaseUrl + 'resources?name=' + name + '&url=' + url + '&format=' + type).success(function(data) {
            var bool = global.toPlaylist();
            $log.info("Data" + data.url + data.name + 'Bool' + bool.value);
            alert('Success');
            if (bool.value) {
              var playlist = global.setList();
              listService.addListElement(data, playlist.value);
              res.push(data);
            };
          }).error(function(error, data, status, config) {
            $log.info("It doesnt work!" + data + config);
          });

        },
        get: function() {
          return search;
        },
        search: function(term) {
          var tmp = $resource(config.apiBaseUrl + 'resources/' + term, {
            id: '@id'
          }, {});
          search = tmp.query();
          return tmp.query();
        },
        show: function(item) {

          // Assign a resource to selected variable.
          global.setResource(item);


        }
      }
    }
  ]);

测试文件:

'use strict';

describe('Service: resource', function() {

  // load the service's module
  beforeEach(module('corsaneApp'));

  // instantiate service
  var $httpBackend;
  var conf;
  var getResource;
  var tmp;
  var resource;

  beforeEach(inject(function($rootScope, _$httpBackend_, $http, config, resourceService) {
    conf = config;
    $httpBackend = _$httpBackend_;
    resource = resourceService;

  }));

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

  it('should return a list of resources', function() {
    $httpBackend.expectGET(conf.apiBaseUrl + 'resources/queen').respond({
      "id": 1,
      "url": "https://en.wikipedia.org/wiki/Elizabeth",
      "text": "no written-explanationobject",
      "name": "queen 1"
    }, {
      "id": 2,
      "url": "https://en.wikipedia.org/wiki/Elizabeth_II",
      "text": "no written-explanationobject",
      "name": "queen 2"
    });
    tmp = resource.search('queen');
    tmp.$promise.then(function(data) {
      getResource = data;
    })
    $httpBackend.flush();

    expect(getResource[0].id).toBe(1);
  });

});

错误讯息:

Chrome 35.0.1916 (Mac OS X 10.9.3) Service: resource should return a list of resources FAILED
    Error: Unexpected request: GET http://localhost:8888/Corsane/web/app_dev.php/api/resources/queen
    No more request expected
        at $httpBackend (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular-mocks/angular-mocks.js:1177:9)
        at sendReq (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:8263:9)
        at $http.serverRequest (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:7995:16)
        at wrappedCallback (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:11485:81)
        at wrappedCallback (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:11485:81)
        at /Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:11571:26
        at Scope.$eval (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:12595:28)
        at Scope.$digest (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular/angular.js:12407:31)
        at Function.$httpBackend.flush (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular-mocks/angular-mocks.js:1435:16)
        at null.<anonymous> (/Users/oyvindhellenes/Documents/Corsane/test/spec/services/resource.js:43:18)
    Error: Unflushed requests: 1
        at Function.$httpBackend.verifyNoOutstandingRequest (/Users/oyvindhellenes/Documents/Corsane/app/bower_components/angular-mocks/angular-mocks.js:1489:13)
        at null.<anonymous> (/Users/oyvindhellenes/Documents/Corsane/test/spec/services/resource.js:24:18)
Chrome 35.0.1916 (Mac OS X 10.9.3): Executed 1 of 1 Chrome 35.0.1916 (Mac OS X 10.9.3): Executed 1 of 1 (1 FAILED) ERROR (0.053 secs / 0.051 secs)
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.

1 个答案:

答案 0 :(得分:3)

它接缝的问题是你在搜索功能中两次调用请求。

您使用$httpBackend.verifyNoOutstandingRequest。它会检查请求的数量是否超出您在测试中所期望的数量。

要解决此问题,您可以尝试下一步更改:

 search: function(term) {
          var tmp = $resource(config.apiBaseUrl + 'resources/' + term, {
            id: '@id'
          }, {});
          search = tmp.query();
          return search;
        },

抱歉,我现在无法自行检查,但它应该可以解决这个问题