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

标签 javascript angularjs

我需要测试一个函数,该函数接受 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

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

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/

相关文章:

javascript - socket.io 中的房间。如何发送消息?

javascript - 如何在 AngularJS 1.x 中对过滤器进行单元测试

asp.net - 回发和回调之间的区别

javascript - 使用对象方法作为事件处理程序

javascript - 用于设置复选框样式的 Angular Directive(指令)

javascript - 将 ng-repeat 值传递给 Ionic Modal

javascript - AngularJS - bootstrap - bootstrapDualListbox - 在左侧选择值时,所有值都选择/移动到右侧

javascript - 如何找到原因 [$injector :modulerr] error in AngularJS?

javascript - knockout 单击绑定(bind)到复选框可防止 jQuery 对值的控制

javascript - 散点图更新 : same number of data points, 但有新的数据点