我正试着用茉莉花测试我的控制器。基本上,当创建控制器时,它将调用一个服务来发出http请求。我正在使用httpBackend获取假数据。当我试图运行测试时,我总是会得到错误“没有挂起的请求刷新”。如果删除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");
});
})发布于 2016-04-05 17:12:18
在“模块的代码”中使用$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你是说..。如果请求没有发出,则会发出请求,当请求做出类似的响应时,则测试失败。
如果您在控制器代码中放置了一些console.log语句,那么在运行测试套件时应该会看到这些日志语句。如果没有,那么您就知道您的控制器代码甚至没有被击中。
也用..。
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});这将迫使测试失败,如果没有达到预期。
发布于 2017-02-09 09:19:53
角度文献提供了关于$httpbackend for ngMockE2E的以下内容:
此外,我们不想像在单元测试期间那样手动清除模拟请求。因此,e2e $httpBackend刷新自动模拟请求,密切模拟XMLHttpRequest对象的行为。
所以,简单地回答:它不存在,你也不需要它。
https://stackoverflow.com/questions/36430979
复制相似问题