无法对ngMockE2E使用httpBackend flush

时间:2016-04-05 15:38:16

标签: angularjs karma-jasmine httpbackend ngmocke2e

我正在尝试使用jasmine测试我的控制器。基本上,当创建控制器时,它将调用服务来发出http请求。我正在使用httpBackend获取虚假数据。当我尝试运行测试时,我总是得到错误"没有待处理的冲洗请求#34;。如果我删除了httpBackend.flush(),则测试失败,因为controller.data.name未定义。任何人都可以知道为什么会这样吗?感谢。

模块的代码在这里:

var myModule = angular.module('myModule', ['ngMockE2E']);
myModule.run(function($httpBackend){
  $httpBackend.whenGET('/Person?content=Manager').respond(function (){
     var response = {'name':'Bob','age':'43'}
     return [200,response];
  })
});

服务代码:

myModule.factory('myService',function($http){
     return {
        getData: function(position){
             return  $http.get('/Person?content='+position); 
        }
     }
});

控制器的代码是:

myModule.controller('myController',function(xrefService){
    var _this = this;
    _this.data ={};
    _this.getData = function(position){
        myService.getData(position).then(function(response){
            _this.data = response.data
        });
    }
    _this.getData("Manager");
})

测试控制器的代码是:

describe("Test Controller",function(){
   var controller,httpBackend,createController;
   beforeEach(module('myModule'));
   beforeEach(inject(function($controller,$httpBackend){      
      createController = function(){
         return $controller('myController');
      }
      httpBackend = $httpBackend;     
   }));
   it("should return data",function(){
      controller = createController();
      httpBackend.flush();
      expect(controller.data.name).toEqual("Bob");
   });      
})

2 个答案:

答案 0 :(得分:1)

angular documentation说明以下关于ngMockE2E的$ httpbackend:

  

此外,我们不想手动冲洗嘲笑   像我们在单元测试期间那样的请求。因此e2e   $ httpBackend会自动刷新模拟出的请求   模拟XMLHttpRequest对象的行为。

所以,简短的回答:它不存在,你不需要它。

答案 1 :(得分:0)

你在“模块的代码”

中使用$ httpBackend.whenGET

你应该在测试代码中使用$ httpBackend,如下所示......

it("should return data",function(){
  $httpBackend.expectGET('/Person?content=Manager').respond(function (){
      var response = {'name':'Bob','age':'43'}
      return [200,response];
  })
  controller = createController();
  httpBackend.flush();
  expect(controller.data.name).toEqual("Bob");
});      

我也建议使用expectGET而不是whenGET。

使用whenGET,你说是否发出了请求,然后回复了。

对于expectGET,你说......如果没有提出请求,将会发出请求,然后请求测试失败。

PS如果在控制器代码中放入一些console.log语句,那么在运行测试套件时应该会看到这些日志语句。如果没有,那么你就知道你的控制器代码甚至没有被击中。

也可以使用..

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

如果未达到预期,将迫使测试失败。

相关问题