Daniel Kaplan
Daniel Kaplan

Reputation: 67450

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()". The problem is, every time the test runs, now() will be a different result. In other libraries, you can set what now() will return for testing purposes. Does moment.js provide a way to do that? I've been googling and not finding any results that say whether or not you can do this.

Upvotes: 0

Views: 473

Answers (2)

caladeve
caladeve

Reputation: 496

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. This returns the number of milliseconds since unix epoch time (1/1/1970).

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

Upvotes: 1

Dr_Derp
Dr_Derp

Reputation: 870

Timekeeper (https://www.npmjs.com/package/timekeeper) fills this exact need.

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);

Upvotes: 3

Related Questions