Files
bitvid/tests/test-helpers/setup-localstorage.mjs
T
google-labs-jules[bot]andPR0M3TH3AN 614e30a61a fix(test): polyfill synchronous requestIdleCallback for unit tests
Fixes flaky/failing unit tests in `tests/state/profile-cache.test.mjs` caused by the recent optimization to defer `localStorage` writes using `requestIdleCallback`.

In the JSDOM environment, `requestIdleCallback` was missing, causing a fallback to `setTimeout`, which introduced asynchronous behavior that the existing tests did not account for.

This change adds a synchronous polyfill for `requestIdleCallback` in `tests/test-helpers/setup-localstorage.mjs`, ensuring that deferred writes happen immediately during testing, restoring deterministic behavior.

Co-authored-by: PR0M3TH3AN <[email protected]>
2026-02-05 23:04:21 +00:00

86 lines
2.2 KiB
JavaScript

if (typeof globalThis.window === "undefined") {
globalThis.window = {};
}
if (typeof globalThis.self === "undefined") {
globalThis.self = globalThis;
}
if (typeof globalThis.WebSocket === "undefined") {
globalThis.WebSocket = class WebSocket {};
}
if (typeof globalThis.navigator === "undefined") {
globalThis.navigator = { userAgent: "node" };
}
if (typeof globalThis.window.WebSocket === "undefined") {
globalThis.window.WebSocket = globalThis.WebSocket;
}
if (typeof globalThis.window.navigator === "undefined") {
globalThis.window.navigator = globalThis.navigator;
}
if (typeof globalThis.localStorage === "undefined") {
const store = new Map();
globalThis.localStorage = {
getItem(key) {
return store.has(key) ? store.get(key) : null;
},
setItem(key, value) {
store.set(String(key), String(value));
},
removeItem(key) {
store.delete(key);
},
clear() {
store.clear();
},
};
}
if (typeof globalThis.window.localStorage === "undefined") {
globalThis.window.localStorage = globalThis.localStorage;
}
// Polyfill requestIdleCallback for synchronous testing if undefined
if (typeof globalThis.requestIdleCallback === "undefined") {
globalThis.requestIdleCallback = (cb) => cb();
globalThis.cancelIdleCallback = () => {};
if (globalThis.window) {
globalThis.window.requestIdleCallback = globalThis.requestIdleCallback;
globalThis.window.cancelIdleCallback = globalThis.cancelIdleCallback;
}
}
if (typeof globalThis.window.crypto === "undefined" && typeof globalThis.crypto !== "undefined") {
globalThis.window.crypto = globalThis.crypto;
}
if (typeof globalThis.structuredClone === "undefined") {
globalThis.structuredClone = (val) => JSON.parse(JSON.stringify(val));
}
if (typeof globalThis.IntersectionObserver === "undefined") {
globalThis.IntersectionObserver = class IntersectionObserver {
constructor(callback) {
this.callback = callback;
}
observe(element) {}
unobserve(element) {}
disconnect() {}
};
}
if (typeof globalThis.ResizeObserver === "undefined") {
globalThis.ResizeObserver = class ResizeObserver {
constructor(callback) {
this.callback = callback;
}
observe(element) {}
unobserve(element) {}
disconnect() {}
};
}