茉莉花角单元测试“无法读取未定义的“属性" [英] Jasmine angular unit test 'Cannot read 'property' of undefined
问题描述
我刚刚开始学习角度单位测试.但是,对具有http调用的函数的测试失败.我已指出问题所在,但无法解决.我知道这是一个简单的问题
I have just started learning angular unit testing. However, this test on a function with http call fails. I have pin pointed the problem but however I am not being able to fix it. I know it's some simple issue
控制器
//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);
});
};
我得到的答复是:
规范
//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();
}); });
如果没有从控制器功能中删除循环,则没有任何错误,并且测试通过.我收到的错误是:
I don't get any errors and the test passes if I remove the loop from the controller function. The error I am getting is:
无法读取未定义的孩子" .从我附带响应数据的图像来看,子级是数组.
Cannot read 'Children' of undefined. From the image I have attached with the response data, children is the array.
推荐答案
运行测试时,$ httpBackend实际上会拦截$http.get
调用并将dummyData
分配给响应,如
When your test is run, $httpBackend actually intercepts the $http.get
call and assign dummyData
to the response as you indicated in
$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
这种嘲笑行为使您的单元测试可以快速完成,而不必依赖于可从测试机访问的reddit.因此,在您的控制器中,response.data = {name: 'Umair'}
且该对象没有名为children
的子代.
This mocking behavior allows your unit tests to be completed quickly without being reliant on reddit being reachable from your test machine. So in your controller, response.data = {name: 'Umair'}
and that object has no child named children
.
要解决此问题,对于dummyData
,请尝试再模拟真实数据.
To fix this, for dummyData
, try mimicking the real data a bit more.
这篇关于茉莉花角单元测试“无法读取未定义的“属性"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!