The commit https://github.com/moment/moment/commit/
f54a32f4c62c12a710335211a73cb002a7249646 and the follow on refactoring https://github.com/moment/moment/commit/
b1d686ed481e2211cb81a1c60eca850fcea93f21 broke the ability for Date mocking libraries ([MockDate](https://www.npmjs.com/package/mockdate), SinonJS, etc.) to mock out the Date object. I believe we should restore this functionality.
```js
const moment = require('moment'),
mockdate = require('mockdate'),
frozenTime = moment();
mockdate.set(frozenTime);
console.log('Frozen time: ', frozenTime.toISOString());
setTimeout(function() {
console.log('Moment time: ', moment().toISOString());
}, 1000);
```
Running the code above will yield the following in `moment@2.10.6` and `moment@2.11.0` respectively.
```bash
$ node index.js
Frozen time: 2016-01-04T14:21:55.335Z
Moment time: 2016-01-04T14:21:55.335Z
$ node index.js
Frozen time: 2016-01-04T14:21:55.335Z
Moment time: 2016-01-04T14:21:56.355Z
```
- Fixes #2857
- Fixes #2855
-export var now = Date.now || function () {
- return +(new Date());
+export var now = function () {
+ return Date.now ? Date.now() : +(new Date());
};
assert.ok(momentNowTime <= afterMomentCreationTime, 'moment now() time should be now, not in the future');
});
+test('now - Date mocked', function (assert) {
+ // We need to test mocking the global Date object, so disable 'Read Only' jshint check
+ /* jshint -W020 */
+ var RealDate = Date,
+ customTimeStr = '2015-01-01T01:30:00.000Z';
+
+ function MockDate() {
+ return new RealDate(customTimeStr);
+ }
+
+ MockDate.now = function () {
+ return new MockDate().valueOf();
+ };
+
+ MockDate.prototype = RealDate.prototype;
+
+ Date = MockDate;
+
+ try {
+ assert.ok(moment().toISOString() === customTimeStr, 'moment now() time should use the global Date object');
+ } finally {
+ Date = RealDate;
+ }
+});
+
test('now - custom value', function (assert) {
var customTimeStr = '2015-01-01T01:30:00.000Z',
customTime = moment(customTimeStr, moment.ISO_8601).valueOf(),