From 5e347dcb91f56637733f81cde75308447b0a7194 Mon Sep 17 00:00:00 2001 From: Carl-Erik Kopseng Date: Fri, 20 Oct 2023 13:55:07 +0200 Subject: [PATCH] Fix for #483 and jestjs/jest#14549 (#485) * Add test from https://github.com/jestjs/jest/issues/14549 * Fix for *Async time forwarders --- src/fake-timers-src.js | 3 +++ test/issue-483-test.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 test/issue-483-test.js diff --git a/src/fake-timers-src.js b/src/fake-timers-src.js index d8c6a6f..0ce7217 100644 --- a/src/fake-timers-src.js +++ b/src/fake-timers-src.js @@ -1578,6 +1578,8 @@ function withGlobal(_global) { function doRun() { originalSetTimeout(function () { try { + runJobs(clock); + let numTimers; if (i < clock.loopLimit) { if (!clock.timers) { @@ -1633,6 +1635,7 @@ function withGlobal(_global) { try { const timer = lastTimer(clock); if (!timer) { + runJobs(clock); resolve(clock.now); } diff --git a/test/issue-483-test.js b/test/issue-483-test.js new file mode 100644 index 0000000..3f6ee87 --- /dev/null +++ b/test/issue-483-test.js @@ -0,0 +1,34 @@ +"use strict"; + +const FakeTimers = require("../src/fake-timers-src"); +const sinon = require("sinon"); +const assert = require("assert"); + +function myFn(cb) { + queueMicrotask(() => cb()); +} + +describe("async time skippers should run microtasks", function () { + let clock; + const timers = ["runAllAsync", "runToLastAsync"]; + + afterEach(function () { + clock.uninstall(); + }); + + beforeEach(function setup() { + clock = FakeTimers.install({ toFake: ["queueMicrotask"] }); + }); + + // eslint-disable-next-line mocha/no-setup-in-describe + timers.forEach((fastForward) => { + it(`should advance past queued microtasks using ${fastForward}`, async function () { + const cb = sinon.fake(); + myFn(cb); + myFn(cb); + myFn(cb); + await clock[fastForward](); + assert.equal(cb.callCount, 3); + }); + }); +});