【发布时间】:2015-07-07 14:09:48
【问题描述】:
我正在尝试创建 Angular 服务,但出现错误。这是服务:
var app = angular.module('plunker', []);
// Filter Service that returns records with crdamt positive:
app.factory('FilterService', function() {
return function(d) {
var filteredData = [];
console.log(d);
d.forEach(function(item)
{
if (item.cramt > 0) {
filteredData.push(item);
}
});
return filteredData;
}
});
在我的单元测试中,我们得到:
it('should return transactions where credit is positive', function() {
var jsonData = {
"transactions": [{
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
}, {
"date": "1/1/2002",
"desc": "Transaction",
"cramt": 110,
"dbamt": 10
}]
};
var filteredRecords = FilterService(jsonData);
expect(filteredRecords).toEqual({
"date": "1/1/2000",
"desc": "Purchase",
"cramt": 50,
"dbamt": 0
});
});
为什么会出错:
TypeError: d.forEach is not a function
【问题讨论】:
-
仅供参考,根据该代码和测试数据,您的测试将失败。
-
要么
d不是数组(在这种情况下它不支持Array.prototype.forEach),要么没有使用适当的现代/垫片 JS 版本(在这种情况下数组不支持 Array.prototype .forEach)。在所有情况下,错误消息都是 100% 正确的。