我正在尝试使用jasmine测试我的控制器。基本上,当创建控制器时,它将调用一个服务来发出http请求。我正在使用httpBackend获取虚假数据。当我尝试运行测试时,我总是会收到错误"No pending request to flush"。如果我删除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");
});
})
angular文档介绍了以下关于ngMockE2E:的$httpbackend
此外,我们不想手动清除模拟请求,就像我们在单元测试中所做的那样。因此,e2e$httpBackend自动、紧密地刷新模拟出的请求模拟XMLHttpRequest对象的行为。
所以,简短的回答是:它不存在,你也不需要它。
您在"模块的代码"中使用$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();
});
如果没有达到预期,这将迫使测试失败。