我是編寫單元測試的新手,需要一些幫助測試函數的一部分。使用moment.js進行單元測試
我的功能看起來像這樣...
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
的屬性,如果有,請將該值轉換爲epoch/unix時間戳,並將其分配給toTime
或fromTime
。所以如果物品有一個叫做end的屬性,其值爲'Sat Oct 31 2015 00:00:00 GMT+0000 (GMT)'
,那麼它將被轉換爲'1446249600'
並分配給toTime
希望這可以解釋它!我不確定如何爲它編寫測試,並希望得到任何幫助/建議。
謝謝!它的工作。也謝謝你的樣品! –