gpt4 book ai didi

javascript - Jasmine Angular 单元测试 'Cannot read ' 未定义的属性'

转载 作者:行者123 更新时间:2023-11-29 19:12:10 25 4
gpt4 key购买 nike

我刚刚开始学习 Angular 单元测试。但是,此对带有 http 调用的函数的测试失败。我已经指出了问题,但是我无法解决它。我知道这是一些简单的问题

Controller

//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);
});

};

我得到的回应是: enter image description here

规范

 //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();


}); });

如果我从 Controller 函数中删除循环,我不会收到任何错误并且测试通过。我得到的错误是:

无法读取未定义的“子项”。从我附上响应数据的图像来看,children 是数组。

最佳答案

当您的测试运行时,$httpBackend 实际上会拦截 $http.get 调用并将 dummyData 分配给您在

中指示的响应
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);

这种模拟行为允许您快速完成单元测试,而不依赖于从您的测试机器访问 reddit。因此,在您的 Controller 中,response.data = {name: 'Umair'} 并且该对象没有名为 children 的子对象。

要解决此问题,对于 dummyData,请尝试更多地模仿真实数据。

关于javascript - Jasmine Angular 单元测试 'Cannot read ' 未定义的属性',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38026741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com