【问题标题】:Testing an Angular Service with Karma not working properly使用 Karma 测试 Angular 服务无法正常工作
【发布时间】:2014-02-03 18:19:43
【问题描述】:

我的测试是:

'use strict';
(function() {
  describe('Service: Summary', function () {
    var $httpBackend;
    // load the service's module
    beforeEach(module('mean'));

    var SummaryService;

    beforeEach(inject(function($injector, _SummaryService_) {
      SummaryService = _SummaryService_;
      $httpBackend = $injector.get('$httpBackend');      
    }));

    // instantiate service
    it('should do something', function () {
      expect(!!SummaryService).toBe(true);
    });

    it('should get a summary', function () {
      $httpBackend.expectGET('/api/ABC').respond(200);
      SummaryService.get();
    });
  });
})();

我的服务是:

'use strict';

angular.module('mean')
.service('SummaryService', ['$http', function SummaryService($http) {
  var summary = this;

  summary.get = function () {
    return $http.get('/api/summary');
  };
}]);

如您所见,它应该转到/api/summary 而不是/api/ABC,但测试仍然通过。我做错了什么?

【问题讨论】:

    标签: angularjs unit-testing karma-runner


    【解决方案1】:

    我建议您在测试中添加以下代码:

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

    第一个将确保实现您定义的所有期望。在您的情况下,$httpBackend.expectGET('/api/ABC') 是一个从未提出过的未完成请求。

    第二个将确保没有更多的请求未被刷新。在您的情况下,$http.get('/api/summary') 永远不会被刷新。

    事实上,在您的测试中,您并没有测试请求。通常的测试用例会执行以下操作:

    1. 定义期望
    2. 检查后端调用的前提条件
    3. 运行将执行后端调用的代码
    4. 刷新 httpBackend ($httpBackend.flush()) 例如后端调用将被填满
    5. 检查发布条件

    您可以更改#2 和#3 的顺序,因为在调用$httpBackend.flush() 之前不会发生后端调用。

    更多信息请参见$httpBackend。

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      相关资源
      最近更新 更多