idraw/__tests__/polyfill/requestanimateframe.ts

46 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2023-02-12 06:44:56 +00:00
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/ban-types */
2021-06-09 06:27:13 +00:00
// https://stackoverflow.com/questions/61593774/how-do-i-test-code-that-uses-requestanimationframe-in-jest
// mock_requestAnimationFrame.js
class RequestAnimationFrameMockSession {
handleCounter = 0;
queue = new Map();
requestAnimationFrame(callback: Function) {
2023-02-12 06:44:56 +00:00
const handle = this.handleCounter++;
this.queue.set(handle, callback);
return handle;
2021-06-09 06:27:13 +00:00
}
cancelAnimationFrame(handle: Function) {
2023-02-12 06:44:56 +00:00
this.queue.delete(handle);
2021-06-09 06:27:13 +00:00
}
2023-02-12 06:44:56 +00:00
triggerNextAnimationFrame(time = performance.now()) {
const nextEntry = this.queue.entries().next().value;
if (nextEntry === undefined) return;
2021-06-09 06:27:13 +00:00
2023-02-12 06:44:56 +00:00
const [nextHandle, nextCallback] = nextEntry;
2021-06-09 06:27:13 +00:00
2023-02-12 06:44:56 +00:00
nextCallback(time);
this.queue.delete(nextHandle);
2021-06-09 06:27:13 +00:00
}
2023-02-12 06:44:56 +00:00
triggerAllAnimationFrames(time = performance.now()) {
while (this.queue.size > 0) this.triggerNextAnimationFrame(time);
2021-06-09 06:27:13 +00:00
}
reset() {
2023-02-12 06:44:56 +00:00
this.queue.clear();
this.handleCounter = 0;
2021-06-09 06:27:13 +00:00
}
2023-02-12 06:44:56 +00:00
}
2021-06-09 06:27:13 +00:00
export const requestAnimationFrameMock = new RequestAnimationFrameMockSession();
2023-02-12 06:44:56 +00:00
window.requestAnimationFrame =
requestAnimationFrameMock.requestAnimationFrame.bind(
requestAnimationFrameMock
);
2021-06-09 06:27:13 +00:00
// @ts-ignore
2023-02-12 06:44:56 +00:00
window.cancelAnimationFrame =
requestAnimationFrameMock.cancelAnimationFrame.bind(
requestAnimationFrameMock
);