Polling
waitFor(fn, options?)
Wait for the callback to execute successfully. If the callback throws an error or returns a rejected promise, it will continue to wait until it succeeds or times out.
This is useful when you need to wait for some asynchronous action to complete, for example, when a server is starting up.
import { waitFor } from "mix-n-matchers/utilities";
const server = { isReady: false };
setTimeout(() => {
server.isReady = true;
}, 100);
await waitFor(
() => {
if (!server.isReady) {
throw new Error("Server not started");
}
},
{
timeout: 500,
interval: 20,
},
);
expect(server.isReady).toBe(true);
Using fake timers
If you're using fake timers, pass an advanceTimers option so the polling loop advances the mocked clock instead of waiting on a real setTimeout, which would never resolve.
import { waitFor } from "mix-n-matchers/utilities";
jest.useFakeTimers();
const server = { isReady: false };
setTimeout(() => {
server.isReady = true;
}, 100);
await waitFor(
() => {
if (!server.isReady) {
throw new Error("Server not started");
}
},
{
timeout: 500,
interval: 20,
advanceTimers: (ms) => jest.advanceTimersByTimeAsync(ms),
},
);
expect(server.isReady).toBe(true);
jest.useRealTimers();
waitUntil(fn, options?)
This is similar to waitFor, but if the callback throws any errors, execution is immediately interrupted and an error message is received. If the callback returns a falsy value, the next check will continue until a truthy value is returned.
This is useful when you need to wait for something to exist before taking the next step.
import { waitUntil } from "mix-n-matchers/utilities";
const element = await waitUntil(() => document.querySelector(".element"), {
timeout: 500,
interval: 20,
});
expect(element?.querySelector(".element-child")).toBeTruthy();
waitUntil also supports the advanceTimers option for use with fake timers, just like waitFor.