作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚刚开始学习 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);
});
};
规范
//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/
我是一名优秀的程序员,十分优秀!