如何模拟AngularJS中的构造函数(特别是Date()构造函数)

How to mock constructors in AngularJS(in particular Date() constructor)

本文关键字:构造函数 特别是 Date AngularJS 模拟 何模拟      更新时间:2023-09-26

我需要测试一个函数,该函数接受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"来模拟构造函数?

还有,有没有更好的测试方法呢?

我尽量不在我的代码中使用DateMath.random

我创建服务来替换它们,这样我就可以通过简单地激活mock模块来模拟我想要的内容。

angular.module('my.date',[])
    .value('Date', Date);
angular.module('my.mock.date',[])
    .value('Date', function(){
        // mock Date code
    });

(当然,您不需要模拟Date的所有功能,只需要模拟您使用的部分…)

参见angular上的这个问题。这是关于stackoverflow的答案