From: Nowell Strite Date: Mon, 4 Jan 2016 14:47:23 +0000 (-0500) Subject: Fix Date mocking regression introduced in 2.11.0 X-Git-Tag: 2.11.1~8^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e6fe681a2bee5f1c13f29d1c83f2ee698b60944e;p=thirdparty%2Fmoment.git Fix Date mocking regression introduced in 2.11.0 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 --- diff --git a/src/lib/moment/now.js b/src/lib/moment/now.js index 42631b597..0f4d0aef0 100644 --- a/src/lib/moment/now.js +++ b/src/lib/moment/now.js @@ -1,3 +1,3 @@ -export var now = Date.now || function () { - return +(new Date()); +export var now = function () { + return Date.now ? Date.now() : +(new Date()); }; diff --git a/src/test/moment/now.js b/src/test/moment/now.js index 35a7ff27c..f10b34863 100644 --- a/src/test/moment/now.js +++ b/src/test/moment/now.js @@ -12,6 +12,31 @@ test('now', function (assert) { 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(),