Handle Fake Timers and IndexedDB safely
mainUsing vi.useFakeTimers() without restrictions can break fake-indexeddb by interfering with its internal async operations, causing tests to hang.
Follow these rules:
- Avoid unrestricted fake timers: Never call
vi.useFakeTimers()without atoFakelist if your code interacts with IndexedDB. - Use specific timer APIs: If you only need to fake certain functions, pass a
toFakearray. - Use
mockDelayfor time-based delays: Instead of fake timers, use themockDelayhelper to makedelayfunctions resolve immediately. This is safer and allows you to assert on the requested delay duration using a spy.
// Only fake specific APIs to avoid breaking IndexedDB
vi.useFakeTimers({ toFake: ['setInterval'] });
vi.useFakeTimers({ toFake: ['Date'] });
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
// Using mockDelay to avoid time-based waits
import { mockDelay } from '__test__/support/helpers/setup';
import { delay as delaySpy } from 'src/shared/helpers/general';
// Call at the top level of the test file
mockDelay();
// Assert that the correct delay was requested
expect(delaySpy).toHaveBeenCalledWith(30000);