简体   繁体   English

我可以分配使用Moment.js的“现在”吗?

[英]Can I assign what “now” is using Moment.js?

I'm using moment.js and I want to write a test that says, "If you do not pass in a date, it returns now() ". 我正在使用moment.js,我想编写一个测试,说:“如果不传递日期,它将返回now() ”。 The problem is, every time the test runs, now() will be a different result. 问题是,每次运行测试时, now()都会得到不同的结果。 In other libraries, you can set what now() will return for testing purposes. 在其他库中,您可以设置now()返回以进行测试。 Does moment.js provide a way to do that? moment.js是否提供了一种方法? I've been googling and not finding any results that say whether or not you can do this. 我一直在搜寻,没有找到任何结果说明您是否可以执行此操作。

Timekeeper ( https://www.npmjs.com/package/timekeeper ) fills this exact need. 计时器( https://www.npmjs.com/package/timekeeper )满足了这一确切需求。

It overrides the date constructors (which moment uses under the hood) so it will work for moment as well. 它会覆盖日期构造函数(此刻在幕后使用),因此它也将暂时起作用。

You can do the following: 您可以执行以下操作:

const timekeeper = require('timekeeper');

const freezeDate = new Date();
timekeeper.freeze(freezeDate);

// in your test
expect(result).to.equal(freezeDate);

You can change the time source (which basically overrides the implementation with a new Date.now ) before each test by doing the following from the official momentjs docs . 您可以在每次测试之前更改时间源(基本上用新的Date.now覆盖实现),方法是通过官方momentjs文档执行以下momentjs This returns the number of milliseconds since unix epoch time (1/1/1970). 这将返回自Unix纪元时间(1/1/1970)以来的毫秒数。

moment.now = function () {
    return +new Date();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM