]> git.ipfire.org Git - thirdparty/moment.git/commitdiff
Fix Date mocking regression introduced in 2.11.0
authorNowell Strite <nowell@strite.org>
Mon, 4 Jan 2016 14:47:23 +0000 (09:47 -0500)
committerIskren Chernev <iskren.chernev@gmail.com>
Sat, 9 Jan 2016 09:42:27 +0000 (11:42 +0200)
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

src/lib/moment/now.js
src/test/moment/now.js

index 42631b5974f0a28b8871278cf49d8d71221b92cf..0f4d0aef0c6f20f9704b76f79649b00a753ad398 100644 (file)
@@ -1,3 +1,3 @@
-export var now = Date.now || function () {
-    return +(new Date());
+export var now = function () {
+    return Date.now ? Date.now() : +(new Date());
 };
index 35a7ff27cb55510d424e7e529bb8609522388a99..f10b34863797d87e644735a6ee6492c71829e8fc 100644 (file)
@@ -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(),