测试$ http Angular服务:没有待清除的待处理请求

时间:2017-03-08 12:17:35

标签: javascript angularjs unit-testing karma-jasmine

我正在尝试为一个返回$ http.get的简单Angular工厂编写一个测试,但我的测试失败了,“没有待处理的请求刷新!”。

我已经按照我在网上找到的一些例子,但没有任何作用。

这是我的服务:

angular.module('MPMReportGenerator')
  .factory('sectionService', function ($http, $log) {
    return {
      getSections: function () {
        return $http
          .get('/MPMReportGenerator/api/categories/all')
          .then(function (response) {
            return response.data
          })
          .catch(function (error) {
            $log.error('ERROR:', error)
            throw error
          })
        }
      }}
    )

这是我的规格:

describe('sectionService', function () {
  'use strict'

  var $httpBackend, sectionService, $rootScope
  beforeEach(function () {
    module('MPMReportGenerator')

    inject(function ($injector) {
      $httpBackend = $injector.get('$httpBackend')
      $rootScope = $injector.get('$rootScope')
    })

    inject(function (_sectionService_) {
      sectionService = _sectionService_
    })
  })

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

  it('should have sectionService service be defined', function () {
    expect(sectionService).toBeDefined()
  })

  it('should get the section list', function () {
    var sections
    $httpBackend.when('GET', '/MPMReportGenerator/api/categories/all').respond(200)
    sectionService.getSections().then(function (data) {
      sections = data
    })
    $rootScope.$digest()
    expect($httpBackend.flush()).doesNotThrow()
  })
})

我做错了什么?

1 个答案:

答案 0 :(得分:0)

删除工厂内的承诺。你无论如何都要在控制器中访问promise。只需返回这样的http请求。

angular.module('MPMReportGenerator')
    .factory('sectionService', function($http, $log) {
        return {
            getSections: function() {
                return $http
                    .get('/MPMReportGenerator/api/categories/all')
            }
        }
    })

像这样访问承诺

 sectionService.getSections().then(function(response) {
    sections = response.data // the values comes under data property so need to access like this.
 })