【发布时间】:2016-12-14 13:53:35
【问题描述】:
我是编写单元测试的新手,需要一些帮助来测试函数的一部分。
我的函数是这样的……
getData() {
return this.parameters.map(p => {
return {
name: p.name,
items: p.items.map(item => {
const toTime = item.hasOwnProperty('end') ? moment.utc(item.end._d).unix() : null;
const fromTime = item.hasOwnProperty('start') ? moment.utc(item.start._d).unix() : null;
return {
id: item.id,
fromTime: fromTime,
toTime: toTime,
};
}),
};
});
}
到目前为止,我的测试看起来像这样(茉莉花)
describe('getData()', function() {
it('should return json data', function() {
$ctrl.parameters = [{
name: 'test',
items: [{
id: 1,
fromTime: null,
toTime: null
}, {
id: 13,
fromTime: null,
toTime: null
}]
}];
expect($ctrl.getData()).toEqual([{
name: 'test',
items: [{
id: 1,
fromTime: null,
toTime: null
}, {
id: 13,
fromTime: null,
toTime: null
}]
}]);
});
});
此测试正在运行/通过,但正如您所见,我没有测试使用 Moment.js 的三元 if/else。基本上,三元组所做的是检查项目是否包含名为start / end 的属性,如果包含,则将该值转换为纪元/unix 时间戳并将其分配给toTime 或fromTime。因此,如果项目有一个名为 end 且值为 'Sat Oct 31 2015 00:00:00 GMT+0000 (GMT)' 的属性,那么它将被转换为 '1446249600' 并分配给 toTime
希望能解释清楚!我不确定如何为其编写测试,并希望得到任何帮助/建议。
【问题讨论】:
标签: javascript unit-testing jasmine