我需要测试一个函数,该函数接受 millisSinceEpoch 并在日期是当前日期时返回时间,否则返回时间。
getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) {
var date = new Date(millisSinceEpoch);
if (date.toLocaleDateString() == new Date().toLocaleDateString()) {
// The replace function removes 'seconds' from the time returned.
return date.toLocaleTimeString().replace(/:\d\d /, ' ');
}
return date.toLocaleDateString();
我希望通过模拟 Date() 构造函数来测试这一点,但我不确定如何使用“原型(prototype)”来模拟构造函数?
另外,有没有更好的方法来测试这个?
最佳答案
我尽量不在代码中使用 Date
或 Math.random
。
我创建服务来替换它们,这样我就可以通过简单地激活模拟模块来模拟我的内心内容。
angular.module('my.date',[])
.value('Date', Date);
angular.module('my.mock.date',[])
.value('Date', function(){
// mock Date code
});
(当然,您不需要模拟所有 Date
功能,只需模拟您使用的部分...)
另请参阅this Angular 问题。和this answer在 stackoverflow 上。
关于javascript - 如何在 AngularJS 中模拟构造函数(特别是 Date() 构造函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25362390/