2017-03-08 55 views
0

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

我跟着我在网上找到的一些例子,但没有任何作品。

这里是我的服务:

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

我在做什么错?

回答

0

删除厂内的承诺。无论如何,您正在控制器中访问诺言。只需返回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. 
}) 
+0

事实上,这是有道理的。但它并没有解决测试问题,但:/ –