【问题标题】:How to mock a resource in a directive unit testing如何在指令单元测试中模拟资源
【发布时间】:2015-06-21 06:39:50
【问题描述】:

我有一个调用资源然后操纵响应的指令。 我的单元测试总是给我“意外的请求 GET”。我尝试了一些方法来模拟这些资源,但没有成功。如果有人知道该怎么做,非常感谢!

;(function(app){
  'use strict';

  app.directive('reportBalance', ['feelingsResource', function(feelingsResource){

    function reportBalanceDirective(scope){
      buildTotalObject(scope);
      getFeelingsTotals(scope);
    }

    function buildTotalObject(scope){
      scope.total = {
        'sad' : 0,
        'happy' : 0,
        getFeelingsTotal : function(){
          return this.sad + this.happy;
        },
        getPercentage: function(feeling) {
          if(!this.getFeelingsTotal())
            return '0%';
          return (this[feeling] / this.getFeelingsTotal() * 100) + '%';
        }
      };
    }

    function getFeelingsTotals(scope){
      feelingsResource.totals({}, function(response){
        onGetFeelingsTotalSuccess(scope, response);
      });
    }

    function onGetFeelingsTotalSuccess(scope, response){
      scope.total.sad = Math.abs(response.totals.sad);
      scope.total.happy = Math.abs(response.totals.happy);
    }

    return {
      restrict: 'E',
      scope: {},
      templateUrl: 'app/commons/directives/reports/balance/report-balance-template.html',
      link: reportBalanceDirective
    };

  }]);

})(app);

这里是规范:

describe("Report Balance Directive:", function() {

  var scope, element;

  beforeEach(function(){
    module('app');
    module('templates');
  });

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = angular.element('<report-balance></report-balance>');
    $compile(element)(scope);
    scope.$digest();
  }));

  it('should contains a "totals" in its scope', function(){
    expect(scope.totals).toBeDefined();
  });

});

错误:

Error: Unexpected request: GET http://localhost:3000/feelings/totals

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive mocking angular-resource


    【解决方案1】:

    好吧,你只需要使用mock $httpBackend,就像任何其他涉及 $http 请求的单元测试一样:

    $httpBackend.whenGET('/feelings/totals').respond(someData);
    

    或者,由于您委托服务进行 $http 查询,因此模拟服务本身:

    spyOn(feelingsResource, 'totals').andCallFake(function(config, callback) {
        callback(someData);
    });
    

    【讨论】:

    • 我不知道是不是因为我的后端在另一个服务器端口上(后端 -p 3000 和前端 -p 9000),但它仍然在做一个意外的请求......无论如何谢谢@jb -nizet 即使使用绝对 url,也不起作用: $httpBackend.whenGET('localhost:3000/feelings/totals').respond(someData);
    • JB 是对的,你应该注入 $httpBackend,使用 whenGET 并保持在相对 URL 中,不要忘记在你的期望之前 $httpBackend.flush()
    猜你喜欢
    • 2016-06-11
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2019-06-25
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多