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.
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);
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.