我一直在寻找最后的日子,但我无法接近解决方案 . 我尝试模拟角度控制器请求的http响应 .
角度控制器:
myController = function ($http, appConfig) {
$http.post(appConfig.restPath+"/administration/imports", {
}).then(function(data){
$scope.pagination = data;
$scope.totalItems = data.data.content.length;
$scope.totalPages = data.data.totalPages;
$scope.pages = [];
$scope.imports = data.data;
for (var i = 0; i < $scope.totalPages; i++){
$scope.pages.push(i);
}
});
}
和测试:
describe('Controller: myController', function() {
// load the controller's module
beforeEach(module("myModule"));
var controller,
scope, httpBackend, myPost;
// Initialize the controller and a mock scope
beforeEach(inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');
myPost = httpBackend.whenPOST('http://localhost:9000/api/v1/administration/imports').respond({data: {content: ["a", "b"], totalPages: "1"}}, "");
scope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
createController = function() {
return $controller(myController, {'$scope' : scope });
};
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should browse the list of imported files', function() {
httpBackend.expectPOST('http://localhost:9000/api/v1/administration/imports');
var controller = createController();
httpBackend.flush();
});
});
但是当我在chrome控制台中检查测试时,他似乎想要服务器询问真实数据(网络流量 - > HTTP请求告诉我,他正在请求服务器而不是加载模拟数据......),但他收到403(禁止) .
我通过业力收到的错误如下:
TypeError: Cannot read property 'length' of undefined at myController.js:35:40
第35行是:
$scope.totalItems = data.data.content.length;
这让我觉得他试图从REST服务加载数据,接收403,空结果(意味着 data == {}
),然后他试图访问未定义的 data.data.content.length
....
正如你所看到我做的完全像谷歌它建议...
https://docs.angularjs.org/api/ngMock/service/ $ httpBackend
SO或其他任何地方的其他示例看起来非常相似 . 我究竟做错了什么?
1 回答
是的,您必须提供真实数据,或者至少您可以提供数据原型,因为您正在测试该单位并且需要长度 .
并删除此部分因为你嘲笑它两次
使用
通过这种方式,您可以确保调用帖子,但如果仍然出现相同的错误,则必须检查响应数据 .