From a6fe19eb26c2b7ed8360de19ca0cc9ae5b05f297 Mon Sep 17 00:00:00 2001 From: Filipe Guerra Date: Wed, 20 Sep 2017 18:21:19 -0700 Subject: [PATCH] Make `now` configurable so time can freeze during backburner run loop This allow us to use fake timers, such as `sinon.useFakeTimers`, to check the state of the app during the run loop. For example: if a popup is supposed to be triggered in X ms from now and it will show to the user during Y ms, then this will allow us to use fake timers to pause between X and Y and check the state of the Ember app at that exact time. This is related with #263, #179 and #166. If someone needs to have the backburner clock separate from the global stubbed clock (as explained in #179), then `_platform.now` config should be used to pass the native `Date.now` function. --- lib/index.ts | 2 +- tests/set-timeout-test.ts | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index adf83788..5a4ace28 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -75,7 +75,7 @@ export default class Backburner { platform.clearTimeout = _platform.clearTimeout || ((id) => clearTimeout(id)); platform.next = _platform.next || ((fn) => platform.setTimeout(fn, 0)); platform.clearNext = _platform.clearNext || platform.clearTimeout; - platform.now = _platform.now || Date.now; + platform.now = _platform.now || (() => Date.now()); this._platform = platform; diff --git a/tests/set-timeout-test.ts b/tests/set-timeout-test.ts index d59cbf0d..5a17c31b 100644 --- a/tests/set-timeout-test.ts +++ b/tests/set-timeout-test.ts @@ -50,17 +50,20 @@ QUnit.test('later', function(assert) { }, 20); }); -QUnit.test('later can continue when `Date.now` is monkey-patched', function(assert) { +QUnit.test('later should rely on stubbed `Date.now`', function(assert) { assert.expect(1); - let arbitraryTime = +new Date(); let bb = new Backburner(['one']); let done = assert.async(); + let globalNowWasUsed = false; - Date.now = function() { return arbitraryTime; }; + Date.now = function() { + globalNowWasUsed = true; + return originalDateNow(); + }; bb.later(() => { - assert.ok(true); + assert.ok(globalNowWasUsed); done(); }, 1); });