Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kerosene: Fix waitForEventLoopToDrain breaking in Jest #107

Merged
merged 1 commit into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/kerosene-ui/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kablamo/kerosene-ui",
"version": "0.0.26",
"version": "0.0.27",
"repository": "https://github.com/KablamoOSS/kerosene/tree/master/packages/kerosene-ui",
"bugs": {
"url": "https://github.com/KablamoOSS/kerosene/issues"
Expand All @@ -22,7 +22,7 @@
},
"dependencies": {
"@babel/runtime": "^7.18.9",
"@kablamo/kerosene": "^0.0.26",
"@kablamo/kerosene": "^0.0.27",
"@types/lodash": "^4.14.184",
"lodash": "^4.17.21"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/kerosene/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kablamo/kerosene",
"version": "0.0.26",
"version": "0.0.27",
"repository": "https://github.com/KablamoOSS/kerosene/tree/master/packages/kerosene",
"bugs": {
"url": "https://github.com/KablamoOSS/kerosene/issues"
Expand Down
20 changes: 17 additions & 3 deletions packages/kerosene/src/function/waitForEventLoopToDrain.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import globalThis from "core-js-pure/features/global-this";

// Grab a reference to the global `setImmediate` so mocking libraries like `sinon` don't interfere
const { setImmediate } = globalThis;
// Grab a reference to the global `setImmediate` and `setTimeout` so mocking libraries like `sinon` don't interfere
const { setImmediate, setTimeout } = globalThis;

/**
* Returns a Promise that resolves when the event loop has drained
Expand All @@ -14,6 +14,20 @@ const { setImmediate } = globalThis;
*/
export default function waitForEventLoopToDrain(): Promise<void> {
return new Promise<void>((resolve) => {
setImmediate(resolve);
if (setImmediate) {
setImmediate(resolve);
} else if (
typeof jest !== "undefined" &&
typeof jest.requireActual === "function"
) {
// jest-environment-jsdom removes `setImmediate` from the Node globals, so instead use jest to require the Node
// API from the "timers" module. We can't just do `import { setImmediate } from "timers";` because of the browser
jest
.requireActual<typeof import("timers")>("timers")
.setImmediate(resolve);
} else {
// Fallback to setTimeout
setTimeout(resolve, 0);
}
});
}