Skip to content

Commit 4d17c3f

Browse files
committed
[scheduler] Improve naive fallback version used in non-DOM environments
Added some tests for the non-DOM version of Scheduler that is used as a fallback, e.g. Jest. The tests use Jest's fake timers API: - `jest.runAllTimers(ms)` flushes all scheduled work, as expected - `jest.advanceTimersByTime(ms)` flushes only callbacks that expire within the given milliseconds. These capabilities should be sufficient for most product tests. Because jest's fake timers do not override performance.now or Date.now, we assume time is constant. This means Scheduler's internal time will not be aligned with other code that reads from `performance.now`. For finer control, the user can override `window._sched` like we do in our tests. We will likely publish a Jest package that has this built in.
1 parent 469005d commit 4d17c3f

File tree

2 files changed

+184
-16
lines changed

2 files changed

+184
-16
lines changed

packages/scheduler/src/Scheduler.js

Lines changed: 39 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -468,30 +468,53 @@ var requestHostCallback;
468468
var cancelHostCallback;
469469
var getFrameDeadline;
470470

471-
// "addEventListener" might not be available on the window object
472-
// if this is a mocked "window" object. So we need to validate that too.
473-
if (
471+
if (typeof window !== 'undefined' && window._schedMock) {
472+
// Dynamic injection, only for testing purposes.
473+
var impl = window._schedMock;
474+
requestHostCallback = impl[0];
475+
cancelHostCallback = impl[1];
476+
getFrameDeadline = impl[2];
477+
} else if (
478+
// If Scheduler runs in a non-DOM environment, it falls back to a naive
479+
// implementation using setTimeout.
474480
typeof window === 'undefined' ||
481+
// "addEventListener" might not be available on the window object
482+
// if this is a mocked "window" object. So we need to validate that too.
475483
typeof window.addEventListener !== 'function'
476484
) {
477-
// If this accidentally gets imported in a non-browser environment, fallback
478-
// to a naive implementation.
479-
var timeoutID = -1;
480-
requestHostCallback = function(callback, absoluteTimeout) {
481-
timeoutID = setTimeout(callback, 0, true);
485+
var _callback = null;
486+
var _currentTime = -1;
487+
var _flushCallback = function(didTimeout, ms) {
488+
if (_callback !== null) {
489+
var cb = _callback;
490+
_callback = null;
491+
try {
492+
_currentTime = ms;
493+
cb(didTimeout);
494+
} finally {
495+
_currentTime = -1;
496+
}
497+
}
498+
};
499+
requestHostCallback = function(cb, ms) {
500+
if (_currentTime !== -1) {
501+
// Protect against re-entrancy.
502+
setTimeout(requestHostCallback, 0, cb, ms);
503+
} else {
504+
_callback = cb;
505+
setTimeout(_flushCallback, ms, true, ms);
506+
setTimeout(_flushCallback, maxSigned31BitInt, false, maxSigned31BitInt);
507+
}
482508
};
483509
cancelHostCallback = function() {
484-
clearTimeout(timeoutID);
510+
_callback = null;
485511
};
486512
getFrameDeadline = function() {
487-
return 0;
513+
return Infinity;
514+
};
515+
getCurrentTime = function() {
516+
return _currentTime === -1 ? 0 : _currentTime;
488517
};
489-
} else if (window._schedMock) {
490-
// Dynamic injection, only for testing purposes.
491-
var impl = window._schedMock;
492-
requestHostCallback = impl[0];
493-
cancelHostCallback = impl[1];
494-
getFrameDeadline = impl[2];
495518
} else {
496519
if (typeof console !== 'undefined') {
497520
// TODO: Remove fb.me link
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/**
2+
* Copyright (c) 2013-present, Facebook, Inc.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @emails react-core
8+
*/
9+
10+
'use strict';
11+
12+
let scheduleCallback;
13+
let runWithPriority;
14+
let ImmediatePriority;
15+
let InteractivePriority;
16+
17+
describe('SchedulerNoDOM', () => {
18+
// If Scheduler runs in a non-DOM environment, it falls back to a naive
19+
// implementation using setTimeout. This only meant to be used for testing
20+
// purposes, like with jest's fake timer API.
21+
beforeEach(() => {
22+
jest.useFakeTimers();
23+
jest.resetModules();
24+
// Delete addEventListener to force us into the fallback mode.
25+
window.addEventListener = undefined;
26+
const Scheduler = require('scheduler');
27+
scheduleCallback = Scheduler.unstable_scheduleCallback;
28+
runWithPriority = Scheduler.unstable_runWithPriority;
29+
ImmediatePriority = Scheduler.unstable_ImmediatePriority;
30+
InteractivePriority = Scheduler.unstable_InteractivePriority;
31+
});
32+
33+
it('runAllTimers flushes all scheduled callbacks', () => {
34+
let log = [];
35+
scheduleCallback(() => {
36+
log.push('A');
37+
});
38+
scheduleCallback(() => {
39+
log.push('B');
40+
});
41+
scheduleCallback(() => {
42+
log.push('C');
43+
});
44+
expect(log).toEqual([]);
45+
jest.runAllTimers();
46+
expect(log).toEqual(['A', 'B', 'C']);
47+
});
48+
49+
it('executes callbacks in order of priority', () => {
50+
let log = [];
51+
52+
scheduleCallback(() => {
53+
log.push('A');
54+
});
55+
scheduleCallback(() => {
56+
log.push('B');
57+
});
58+
runWithPriority(InteractivePriority, () => {
59+
scheduleCallback(() => {
60+
log.push('C');
61+
});
62+
scheduleCallback(() => {
63+
log.push('D');
64+
});
65+
});
66+
67+
expect(log).toEqual([]);
68+
jest.runAllTimers();
69+
expect(log).toEqual(['C', 'D', 'A', 'B']);
70+
});
71+
72+
it('advanceTimersByTime expires callbacks incrementally', () => {
73+
let log = [];
74+
75+
scheduleCallback(() => {
76+
log.push('A');
77+
});
78+
scheduleCallback(() => {
79+
log.push('B');
80+
});
81+
runWithPriority(InteractivePriority, () => {
82+
scheduleCallback(() => {
83+
log.push('C');
84+
});
85+
scheduleCallback(() => {
86+
log.push('D');
87+
});
88+
});
89+
90+
expect(log).toEqual([]);
91+
jest.advanceTimersByTime(249);
92+
expect(log).toEqual([]);
93+
jest.advanceTimersByTime(1);
94+
expect(log).toEqual(['C', 'D']);
95+
96+
log = [];
97+
98+
jest.runAllTimers();
99+
expect(log).toEqual(['A', 'B']);
100+
});
101+
102+
it('calls immediate callbacks immediately', () => {
103+
let log = [];
104+
105+
runWithPriority(ImmediatePriority, () => {
106+
scheduleCallback(() => {
107+
log.push('A');
108+
scheduleCallback(() => {
109+
log.push('B');
110+
});
111+
});
112+
});
113+
114+
expect(log).toEqual(['A', 'B']);
115+
});
116+
117+
it('handles errors', () => {
118+
let log = [];
119+
120+
expect(() => {
121+
runWithPriority(ImmediatePriority, () => {
122+
scheduleCallback(() => {
123+
log.push('A');
124+
throw new Error('Oops A');
125+
});
126+
scheduleCallback(() => {
127+
log.push('B');
128+
});
129+
scheduleCallback(() => {
130+
log.push('C');
131+
throw new Error('Oops C');
132+
});
133+
});
134+
}).toThrow('Oops A');
135+
136+
expect(log).toEqual(['A']);
137+
138+
log = [];
139+
140+
// B and C flush in a subsequent event. That way, the second error is not
141+
// swallowed.
142+
expect(() => jest.runAllTimers()).toThrow('Oops C');
143+
expect(log).toEqual(['B', 'C']);
144+
});
145+
});

0 commit comments

Comments
 (0)