I want to write a jest unit test for a module that uses requestAnimationFrame
and cancelAnimationFrame
.
I tried overriding window.requestAnimationFrame with my own mock (as suggested in this answer), but the module keeps on using the implementation provided by jsdom.
My current approach is to use the (somehow) builtin requestAnimationFrame
implementation from jsdom, which seems to use setTimeout
under the hood, which should be mockable by using jest.useFakeTimers()
.
jest.useFakeTimers();
describe("fakeTimers", () => {
test.only("setTimeout and trigger", () => {
const order: number[] = [];
expect(order).toEqual([]);
setTimeout(t => order.push(1));
expect(order).toEqual([]);
jest.runAllTimers();
expect(order).toEqual([1]);
});
test.only("requestAnimationFrame and runAllTimers", () => {
const order: number[] = [];
expect(order).toEqual([]);
requestAnimationFrame(t => order.push(1));
expect(order).toEqual([]);
jest.runAllTimers();
expect(order).toEqual([1]);
});
});
The first test is successful, while the second fails, because order
is empty.
What is the correct way to test code that relies on requestAnimationFrame()
. Especially if I need to test conditions where a frame was cancelled?