我刚刚开始学习角度单元测试。但是,对具有 http 调用的函数的此测试失败。我已经指出了问题,但我无法解决它。我知道这是一个简单的问题
控制器
//Get data from URL
vm.getJson = function() {
var url = 'https://www.reddit.com/r/worldnews/new.json',
count = 0;
$http.get(url).success(function(response) {
console.log(response);
for (var i = 0; i < response.data.children.length; i++) {
vm.data.push(response.data.children[i].data);
count++;
if (count === response.data.children.length) {
vm.numberOfPages();
}
}
vm.result = true;
}).error(function(err) {
console.log(err);
});
};
The response I am getting is:
Spec
//Testing the getJson function
describe('vm.getJson()', function() {
it('It should return dummy Data as response and vm.result to be truthy', function() {
var dummyData = {name: 'Umair'};
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
MainCtrl.getJson();
$httpBackend.flush();
expect(MainCtrl.result).toBeTruthy();
}); });
如果我从控制器函数中删除循环,我不会收到任何错误并且测试通过。我收到的错误是:
无法读取未定义的“子级”。从我附加的响应数据图像来看,children 是数组。
当你的测试运行时,$httpBackend实际上拦截了$http.get
调用并分配dummyData
到您在中指出的答复
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
这种模拟行为可以让您的单元测试快速完成,而无需依赖于测试机器上可访问的 reddit。所以在你的控制器中,response.data = {name: 'Umair'}
并且该对象没有名为的子对象children
.
为了解决这个问题,对于dummyData
,尝试更多地模仿真实数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)