mirror of
https://github.com/scratchfoundation/scratch-vm.git
synced 2025-01-09 06:21:59 -05:00
Use MockTimer for TaskQueue tests
This commit is contained in:
parent
7f80fe17b3
commit
46a1ae83a0
2 changed files with 25 additions and 14 deletions
|
@ -154,7 +154,7 @@ class TaskQueue {
|
|||
}
|
||||
resolve();
|
||||
};
|
||||
this._timeout = timeout = setTimeout(onTimeout, estimatedWait);
|
||||
this._timeout = timeout = this._timer.setTimeout(onTimeout, estimatedWait);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,16 +1,17 @@
|
|||
const test = require('tap').skip;
|
||||
const test = require('tap').test;
|
||||
|
||||
const TaskQueue = require('../../src/util/task-queue');
|
||||
|
||||
const MockTimer = require('../fixtures/mock-timer');
|
||||
const testCompare = require('../fixtures/test-compare');
|
||||
|
||||
test('constructor', t => {
|
||||
// Max tokens = 1000, refill 1000 tokens per second (1 per millisecond), and start with 0 tokens
|
||||
const bukkit = new TaskQueue(1000, 1000, 0);
|
||||
|
||||
// Simulate time passing with a stubbed timer
|
||||
const simulatedTimeStart = Date.now();
|
||||
bukkit._timer = {timeElapsed: () => Date.now() - simulatedTimeStart};
|
||||
const mockTimer = new MockTimer();
|
||||
bukkit._timer = mockTimer;
|
||||
mockTimer.start();
|
||||
|
||||
const taskResults = [];
|
||||
const promises = [];
|
||||
|
@ -25,16 +26,26 @@ test('constructor', t => {
|
|||
);
|
||||
bukkit.cancelAll();
|
||||
promises.push(
|
||||
bukkit.do(() => taskResults.push('a'), 50).then(() =>
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait')
|
||||
),
|
||||
bukkit.do(() => taskResults.push('b'), 10).then(() =>
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial')
|
||||
),
|
||||
bukkit.do(() => taskResults.push('c'), 1).then(() =>
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '<', 80, 'Cheap task should run soon')
|
||||
)
|
||||
bukkit.do(() => taskResults.push('a'), 50).then(() => {
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '>=', 50, 'Costly task must wait');
|
||||
}),
|
||||
bukkit.do(() => taskResults.push('b'), 10).then(() => {
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '>=', 60, 'Tasks must run in serial');
|
||||
}),
|
||||
bukkit.do(() => taskResults.push('c'), 1).then(() => {
|
||||
testCompare(t, bukkit._timer.timeElapsed(), '<=', 80, 'Cheap task should run soon');
|
||||
})
|
||||
);
|
||||
|
||||
// advance 10 simulated milliseconds per JS tick
|
||||
const step = () => {
|
||||
mockTimer.advanceMockTime(10);
|
||||
if (mockTimer.timeElapsed() < 100) {
|
||||
global.setTimeout(step, 0);
|
||||
}
|
||||
};
|
||||
step();
|
||||
|
||||
return Promise.all(promises).then(() => {
|
||||
t.deepEqual(taskResults, [goodCancelMessage, 'a', 'b', 'c'], 'All tasks must run in correct order');
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue