Async tests and flaky tests
How to test async code without false passes or random failures: awaiting everything, findBy and waitFor, what the act() warning means, Vitest fake timers and their async variants, why tests flake (timing, shared state, order, network, randomness, time zones) and how to find and fix them instead of retrying.
Reading level
Shows sections up to the selected level.
This topic starts at Junior level.
Tests that pass without checking anything
Test runner yalnız test funksiyasının ona qaytardığını qiymətləndirə bilir. Funksiya asinxron iş bitməmiş qayıdırsa, runner heç bir xəta görmür və testi keçmiş sayır.
test("loads the user", () => {
fetchUser(1).then((user) => {
expect(user.name).toBe("Ana");
});
});Funksiya sorğunu başladır və dərhal undefined qaytarır, ona görə test keçir. Assertion sonra işləyir, ya da ümumiyyətlə işləmir. Düşəndə xəta heç kimin emal etmədiyi rejected promise olur: Vitest emal olunmamış rejection-ları bu testin uğursuzluğu kimi yox, bütün run-ın xətası kimi bildirir; test faylı sorğudan əvvəl bitsə, assertion heç vaxt işləməyə bilər.
Testi yoxladığı işi gözləməyə məcbur et:
test("loads the user", async () => {
const user = await fetchUser(1);
expect(user.name).toBe("Ana");
});Promise-i qaytarmaq (return fetchUser(1).then(...)) da işləyir, amma async/await daha asan oxunur.
UI testlərində eyni bug
awaitolmadanuser.click(button): növbəti sətir klik bitməmiş işləyir.expect(screen.queryByText("Could not delete")).not.toBeInTheDocument()kimi yoxluq yoxlaması onda keçir, çünki hələ heç nə baş verməyib.awaitolmadan ayrıca sətir kimi yazılmışscreen.findByText("Saved"): onu heç nə gözləmir və nəticəni heç nə yoxlamır.awaitolmadanwaitFor(() => expect(...)): onun içindəki timeout testi heç vaxt uğursuz edə bilməz.awaitolmadanexpect(promise).resolves.toBe(...): Vitest bunu aşkar edir və testi sonunda uğursuz edir, digərləri isə gözdən qaçır.
Qoruyucular
expect.hasAssertions()heç bir assertion işləməyən testi uğursuz edir;expect.assertions(2)isə dəqiq say tələb edir. Hər ikisi ilə yuxarıdakı ilk nümunə düşür: test bitəndə heç bir assertion işləməyib.expect.requireAssertionsconfig seçimi "ən azı bir" qaydasını bütün testlərə tətbiq edir.- typescript-eslint-in
no-floating-promisesqaydası await olunmayan, qaytarılmayan və emal olunmayan promise ifadələrini bildirir. - eslint-plugin-testing-library-də
findBy, user-event vəwaitForüçünawait-async-queries,await-async-eventsvəawait-async-utilsqaydaları var. - Hər yeni testin bir dəfə düşdüyünü öz gözünlə gör. Heç vaxt düşdüyünü görmədiyin test heç nəyi yoxlamaya bilər.
A test runner can only judge what the test function gives back. If the function returns before the async work is done, the runner sees no error and marks the test as passed.
test("loads the user", () => {
fetchUser(1).then((user) => {
expect(user.name).toBe("Ana");
});
});The function starts the request and returns undefined straight away, so the test passes. The assertion runs later, if at all. When it fails, the error is a rejected promise that nobody handles: Vitest reports unhandled rejections as errors of the whole run, not as a failure of this test, and if the test file finishes before the request does, the assertion may never run.
Make the test wait for the work it checks:
test("loads the user", async () => {
const user = await fetchUser(1);
expect(user.name).toBe("Ana");
});Returning the promise (return fetchUser(1).then(...)) works too; async/await is easier to read.
The same bug in UI tests
user.click(button)withoutawait: the next line runs before the click has finished. An absence check such asexpect(screen.queryByText("Could not delete")).not.toBeInTheDocument()then passes, because nothing has happened yet.screen.findByText("Saved")as a statement withoutawait: nothing waits for it and nothing checks the result.waitFor(() => expect(...))withoutawait: a timeout inside it can never fail the test.expect(promise).resolves.toBe(...)withoutawait: Vitest detects this one and fails the test at the end, but the others go unnoticed.
Guards
expect.hasAssertions()fails a test in which no assertion ran;expect.assertions(2)demands an exact count. With either one, the first example above fails: no assertion has run when the test ends. Theexpect.requireAssertionsconfig option applies the "at least one" rule to every test.- typescript-eslint's
no-floating-promisesreports promise statements that are not awaited, returned or handled. - eslint-plugin-testing-library has
await-async-queries,await-async-eventsandawait-async-utilsforfindBy, user-event andwaitFor. - Watch every new test fail once. A test you have never seen fail may not be testing anything.
Waiting for the UI: findBy and waitFor
UI sorğudan, taymerdən və ya effektdən sonra dəyişəndə test gözləməlidir. Ağla gələn ilk yol sabit fasilədir:
await new Promise((resolve) => setTimeout(resolve, 500));
expect(screen.getByText("Saved")).toBeInTheDocument();Sürətli noutbukda bu, vaxt itkisidir; yüklü CI maşınında isə 500 ms bəzən çatmır və test flaky olur. Martin Fowler-in məsləhəti asinxron cavabları heç vaxt sadəcə sleep ilə gözləməmək, əvəzində callback və ya polling işlətməkdir. Testing Library-nin gözləmə köməkçiləri polling-i sənin yerinə edir.
findBy
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("status")).toHaveTextContent("Saved");findBy element görünən kimi resolve olur, default olaraq 1000 ms-dən sonra isə reject olur. Gözləmə seçimlərini üçüncü arqument kimi qəbul edir: findByRole("status", {}, { timeout: 3000 }).
waitFor
waitFor(callback) ümumi formadır. Callback-i dərhal işə salır, sonra hər 50 ms-dən bir və DOM hər dəfə dəyişəndə təkrarlayır; bu, callback xəta atmağı dayandırana və ya timeout (1000 ms) bitənə qədər davam edir. Sonra sonuncu xəta ilə reject olur.
await waitFor(() => expect(onSave).toHaveBeenCalledWith({ name: "Ana" }));false qaytarmaq kifayət deyil: təkrar cəhd olunması üçün callback xəta atmalıdır. expect-in onun içində olmasının səbəbi budur. Yox olmalı olan element üçün waitForElementToBeRemoved(() => screen.queryByText("Loading...")) element itənə qədər gözləyir. Element əvvəldən yoxdursa, o, dərhal xəta atır və bu, səhv şeyi gözləyən testi tutur.
Gözləməni etibarlı saxlayan qaydalar
Kent C. Dodds bunları Testing Library ilə bağlı tipik səhvlər sırasında sadalayır:
waitForiləgetByəvəzinəfindBy-a üstünlük ver. Davranış eynidir, kod qısadır, xəta mesajı daha yaxşıdır.- Heç vaxt boş callback ötürmə (
await waitFor(() => {})). O, heç nəyi yoxlamır və asinxron məntiq dəyişən kimi test sınır. Konkret assertion gözlə. - Callback-ə bir assertion qoy. Heç vaxt keçməyəcək assertion eyni callback-dədirsə,
waitForuğursuzluğu bildirməzdən əvvəl timeout bitənə qədər təkrar cəhd edir. Qalanlarını gözləmədən sonra yoxla, orada dərhal düşsünlər. - Yan təsirləri callback-dən kənarda saxla.
waitFor-un içindəki klik hər təkrar cəhddə yenidən işləyir.
When the UI changes after a request, a timer or an effect, the test has to wait. The tempting way is a fixed pause:
await new Promise((resolve) => setTimeout(resolve, 500));
expect(screen.getByText("Saved")).toBeInTheDocument();On a fast laptop that wastes time; on a busy CI machine 500 ms is sometimes not enough, and the test flakes. Martin Fowler's advice is to "never use bare sleeps" and to use a callback or polling instead. Testing Library's waiting helpers are polling done for you.
findBy
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("status")).toHaveTextContent("Saved");findBy resolves as soon as the element appears and rejects after 1000 ms by default. It takes the wait options as a third argument: findByRole("status", {}, { timeout: 3000 }).
waitFor
waitFor(callback) is the general form. It runs the callback immediately, then again every 50 ms and whenever the DOM changes, until the callback stops throwing or the timeout (1000 ms) passes. Then it rejects with the last error.
await waitFor(() => expect(onSave).toHaveBeenCalledWith({ name: "Ana" }));Returning false is not enough: the callback has to throw to be retried. That is why expect belongs inside it. For something that should disappear, waitForElementToBeRemoved(() => screen.queryByText("Loading...")) waits until the element is gone. It throws at once if the element is not there to begin with, which catches a test that waits for the wrong thing.
Rules that keep waiting reliable
Kent C. Dodds lists these among the common mistakes with Testing Library:
- Prefer
findByoverwaitForplusgetBy. Same behaviour, shorter, with a better error message. - Never pass an empty callback (
await waitFor(() => {})). It checks nothing, and the test breaks as soon as the async logic changes. Wait for a specific assertion. - Put one assertion in a callback. If an assertion that will never pass shares the callback,
waitForkeeps retrying until the timeout before it reports the failure. Assert the rest after the wait, where they fail at once. - Keep side effects out of the callback. A click inside
waitForruns again on every retry.
What the act() warning means
React-in act() funksiyası onun içində başlayan yenilənmələrin və effektlərin növbəti sətir işləməzdən əvvəl tətbiq olunmasını təmin edir, yəni istifadəçinin ekranı görəcəyi andakı vəziyyəti yaradır. React Testing Library render-i və fireEvent-i act-ə bükür, user-event-in event-ləri də eyni wrapper-dən keçir, waitFor və findBy gözləyərkən isə o, act yoxlamasını söndürür ki, gözləmə zamanı baş verən yenilənmələr xəbərdarlıq yaratmasın. Testlərin çoxu act-i heç vaxt özü çağırmır.
Xəbərdarlıq belə görünür:
An update to ProfileForm inside a test was not wrapped in act(...).Bu o deməkdir ki, React testdə heç nəyin gözləmədiyi state yenilənməsi görüb. Adətən test assertion-larını edib irəli gedir, komponentin başlatdığı promise isə hələ gözləmədə olur və sonra state dəyişir. Test UI-ı o sabitləşməmiş yoxlayıb, yenilənmə isə testin idarə etmədiyi anda baş verir.
test("saves the profile", async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
render(<ProfileForm onSave={onSave} />);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(onSave).toHaveBeenCalled();
// onSave bu sətirdən sonra resolve olur və form "Saved" qoyur: xəbərdarlıq
});Düzəliş daha çox act deyil, istifadəçinin gözləyəcəyini gözləməkdir:
expect(await screen.findByRole("status")).toHaveTextContent("Saved");İndi yenilənmə Testing Library gözləyərkən baş verir və test son vəziyyəti də yoxlayır.
act-i özün nə vaxt çağırırsan
- Fake timer-lər: onları irəli çəkmək heç bir Testing Library çağırışından kənarda state dəyişə bilən callback-ləri işə salır:
act(() => { vi.advanceTimersByTime(5000); }). - Testin birbaşa yaratdığı yenilənmələr, məsələn store-un metodunu və ya
renderHooknəticəsinin funksiyasını çağırmaq.
Asinxron iş üçün react.dev async formanı tövsiyə edir: await act(async () => { ... }). React 19-da act-i react-dən import et; react-dom/test-utils-dən köhnə import deprecated-dir.
Mühit bayrağı
React 18 globalThis.IS_REACT_ACT_ENVIRONMENT bayrağını gətirdi; React act-dən kənar yenilənmələri yalnız bu bayraq true olanda bildirir. React Testing Library onu qlobal beforeAll-da qoyur, ona görə Vitest-də ya globals: true təyin et, ya da bayrağı setup faylında özün qoy. Əks halda xəbərdarlıq heç vaxt görünmür, onun göstərdiyi problem isə gizli qalır.
Xəbərdarlığı susdurma. O, testinin gözləmədiyi yenilənməni göstərir və sonradan flaky testə çevrilən çox vaxt məhz həmin yenilənmə olur.
React's act() makes sure that the updates and effects triggered inside it have been applied before your next line runs, the way they would be by the time a user sees the screen. React Testing Library wraps render and fireEvent in act, user-event's events go through the same wrapper, and while waitFor and findBy wait, it turns the act check off so updates during the wait do not warn. Most tests never call act themselves.
The warning looks like this:
An update to ProfileForm inside a test was not wrapped in act(...).It means React saw a state update that nothing in the test was waiting for. Usually the test made its assertions and moved on while a promise started by the component was still pending, and that promise later set state. The test checked the UI before it had settled, and the update lands at a moment the test does not control.
test("saves the profile", async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
render(<ProfileForm onSave={onSave} />);
await user.click(screen.getByRole("button", { name: "Save" }));
expect(onSave).toHaveBeenCalled();
// onSave resolves after this line, and the form sets "Saved": the warning
});The fix is not more act, but waiting for what the user would wait for:
expect(await screen.findByRole("status")).toHaveTextContent("Saved");Now the update happens while Testing Library is waiting, and the test checks the final state too.
When you call act yourself
- Fake timers: advancing them runs callbacks that may set state, outside any Testing Library call:
act(() => { vi.advanceTimersByTime(5000); }). - Updates the test triggers directly, such as calling a store's method or a
renderHookresult's function.
For async work, react.dev recommends the async form, await act(async () => { ... }). In React 19, import act from react; the old import from react-dom/test-utils is deprecated.
The environment flag
React 18 introduced globalThis.IS_REACT_ACT_ENVIRONMENT; React reports updates outside act only when it is true. React Testing Library sets it in a global beforeAll, so with Vitest set globals: true or set the flag in your setup file. Otherwise the warning never appears, and the problem it points at stays hidden.
Do not silence the warning. It points at an update your test did not wait for, and that update is often what turns into a flaky test later.
Fake timers in Vitest
5 saniyədən sonra gizlənən bildiriş, 300 ms-lik və ya 15 dəqiqədən sonra çıxan sessiya xəbərdarlığı: bunları real vaxtda gözləmək testləri yavaşladır, onlarla yarışmaq isə testləri flaky edir. taymer funksiyalarını yalnız test irəli çəkəndə hərəkət edən saatla əvəz edir.
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test("hides the notice after 5 seconds", () => {
render(<SavedNotice />);
act(() => {
vi.advanceTimersByTime(4999);
});
expect(screen.getByRole("status")).toHaveTextContent("Saved");
act(() => {
vi.advanceTimersByTime(1);
});
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});Test millisaniyələr çəkir və sərhədin hər iki tərəfini yoxlayır. act ona görə var ki, taymer callback-i state-i heç bir Testing Library çağırışından kənarda dəyişir.
Nələr saxtalaşdırılır
vi.useFakeTimers() setTimeout, setInterval, setImmediate, onların clear funksiyalarını, Date-i, default olaraq isə mühitin təqdim etdiyi bu növdən olan digər hər şeyi, məsələn requestAnimationFrame və performance-ı saxtalaşdırır; istisna process.nextTick və queueMicrotask-dır. Promise-lər taymer deyil: promise callback-ləri yenə də kimi, öz qaydası ilə işləyir.
Saatı irəli çəkmək
vi.advanceTimersByTime(ms):msərzində vaxtı çatan bütün taymerləri işə salır.vi.advanceTimersToNextTimer(): növbəti taymerə keçir və onu işə salır.vi.runOnlyPendingTimers(): artıq planlaşdırılmış taymerləri işə salır, onların yaratdığı yeniləri yox.vi.runAllTimers(): taymer qalmayana qədər işə salır. Sonsuz interval onu 10 000 taymerdən sonra xəta atmağa məcbur edir (loopLimitseçimi).vi.getTimerCount(): neçə taymerin gözlədiyini göstərir. Komponentin özündən sonra təmizlik etdiyini yoxlamaq üçün faydalıdır.vi.setSystemTime(date): heç bir taymeri işə salmadanDate.now()vənew Date()-in qaytardığını dəyişir. "Bu gün" və "ayın sonu" halları üçün alət budur.
Söndürmək
vi.useRealTimers() real funksiyaları geri qaytarır, hələ planlaşdırılmış taymerlər isə atılır. Testing Library-nin bələdçisi əvvəlcə gözləyən taymerləri işə salmağı təklif edir ki, yazmadığın kitabxananın planlaşdırdığı iş səssizcə itməsin. Real taymerləri hər testdən sonra bərpa et; növbəti testə sızan fake timer-lər çaşdırıcı uğursuzluqların klassik səbəbidir.
Fake timer-lər həmişə daha yaxşı seçim deyil. Gecikmə qısadırsa, real taymerlər və findBy çox vaxt daha sadədir.
A notice that hides after 5 seconds, a of 300 ms or a session warning after 15 minutes: waiting for these in real time makes tests slow, and racing them makes tests flaky. replace the timer functions with a clock that only moves when the test moves it.
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test("hides the notice after 5 seconds", () => {
render(<SavedNotice />);
act(() => {
vi.advanceTimersByTime(4999);
});
expect(screen.getByRole("status")).toHaveTextContent("Saved");
act(() => {
vi.advanceTimersByTime(1);
});
expect(screen.queryByRole("status")).not.toBeInTheDocument();
});The test takes milliseconds and checks both sides of the boundary. act is there because the timer callback sets state outside any Testing Library call.
What gets faked
vi.useFakeTimers() fakes setTimeout, setInterval, setImmediate, their clear functions, Date, and by default everything else of that kind the environment provides, such as requestAnimationFrame and performance, except process.nextTick and queueMicrotask. Promises are not timers: promise callbacks still run as , on their own schedule.
Moving the clock
vi.advanceTimersByTime(ms): runs every timer that falls due withinms.vi.advanceTimersToNextTimer(): jumps to the next timer and runs it.vi.runOnlyPendingTimers(): runs the timers already scheduled, but not new ones they create.vi.runAllTimers(): runs timers until none are left. An endless interval makes it throw after 10,000 timers (theloopLimitoption).vi.getTimerCount(): how many timers are waiting. Useful to check that a component cleaned up.vi.setSystemTime(date): changes whatDate.now()andnew Date()return without running any timers. It is the tool for "today" and "end of the month" cases.
Turning them off
vi.useRealTimers() restores the real functions, and timers still scheduled are discarded. Testing Library's guide suggests running the pending timers first, so work scheduled by a library you did not write is not silently lost. Restore real timers after every test; fake timers that leak into the next test are a classic cause of confusing failures.
Fake timers are not always the better choice. If the delay is short, real timers with findBy are often simpler.
When fake timers meet promises
Fake timer-lərlə bağlı sürprizlərin çoxu taymerləri və promise-ləri qarışdıran koddan gəlir. Status yoxlayan poller-ə bax:
export function startPolling(load: () => Promise<string>, show: (status: string) => void) {
async function poll() {
const status = await load();
show(status);
if (status !== "done") setTimeout(poll, 1000);
}
setTimeout(poll, 1000);
}Fake timer-lər aktivdir, load isə ardıcıl olaraq "queued", "running" və "done" qaytarır. Test vi.advanceTimersByTime(3000) çağırır və üç yenilənmə gözləyir, amma bir dənə alır. İlk poll 1000 ms-də işə düşür və await load()-da dayanır; poll-un qalanı promise callback-idir, yəni microtask-dır, microtask-lar isə yalnız sinxron advanceTimersByTime qayıtdıqdan sonra işləyir. O vaxta qədər o, aralıqda başqa taymer tapmayıb, ona görə saat sadəcə 3000 ms-ə keçib. Növbəti taymer daha sonra, yeni vaxtdan planlaşdırılır. Bu, adi qaydada işləyən -dur: taymerlər macrotask-dır, promise callback-ləri isə onların arasında işləyir.
Async variantlar bunu düzəldir. Vitest sənədlərinə görə vi.advanceTimersByTimeAsync asinxron qurulan taymerləri də əhatə edir: taymerlərin arasında promise callback-lərinin işləməsinə imkan verir. advanceTimersByTime, advanceTimersToNextTimer, runAllTimers və runOnlyPendingTimers-in hər birinin Async versiyası var. React testində onu async act-ə bük:
await act(async () => {
await vi.advanceTimersByTimeAsync(3000);
});Fake timer-lər altında user-event və Testing Library
Hər ikisi Jest-in fake timer-ləri nəzərə alınaraq qurulub və bu, Vitest-də özünü göstərir:
- user-event input-lar arasında
setTimeoutilə fasilə verir (delayseçimi, default 0), fake timer-lər altında isə bu timeout-u heç nə işə salmır. Onun sənədləri saatını ötürməyi deyir,userEvent.setup({ advanceTimers: vi.advanceTimersByTime }), köhnədelay: nullüsulunu isə məsləhət görmür. waitFor,findByvə user-event çağırışlarının hamısının keçdiyi React Testing Library async wrapper-i qısasetTimeoutilə bitir və onu yalnız Jest-in fake timer-lərini aşkar edəndə irəli çəkir. Vitest-in fake timer-ləri altında bu çağırışlaradvanceTimersqoyulsa belə test timeout-a düşənə qədər ilişib qala bilər. Bu, React Testing Library repozitoriyasında açıq issue-dur.
Etibarlı yol: fake timer tələb edən testləri sinxron saxla, qarşılıqlı əlaqə üçün fireEvent, vaxtı irəli çəkmək üçün act(() => { vi.advanceTimersByTime(...); }), yoxlamaq üçün isə getBy işlət. user-event və findBy lazım olan testlərə real taymerlər ver. vi.useFakeTimers({ shouldAdvanceTime: true }) də onları ilişib qalmaqdan qurtarır, amma onda real vaxt saxta saata sızır. Vitest-in öz vi.waitFor, vi.waitUntil və expect.poll köməkçiləri isə gözləyərkən fake timer-ləri irəli çəkir.
Fake timer-ləri test olunan kod nəyisə planlaşdırmazdan əvvəl, adətən render-dən əvvəl yandır. Real setTimeout ilə yaradılmış taymer real qalır.
Most surprises with fake timers come from code that mixes timers and promises. Take a status poller:
export function startPolling(load: () => Promise<string>, show: (status: string) => void) {
async function poll() {
const status = await load();
show(status);
if (status !== "done") setTimeout(poll, 1000);
}
setTimeout(poll, 1000);
}With fake timers on and load returning "queued", "running" and "done", a test calls vi.advanceTimersByTime(3000) and expects three updates. It gets one. The first poll runs at 1000 ms and stops at await load(); the rest of poll is a promise callback, a microtask, and microtasks run only after the synchronous advanceTimersByTime has returned. By then it found no other timer in the range, so the clock simply moved to 3000 ms. The next timer is scheduled later, from the new time. This is the working as usual: timers are macrotasks, and promise callbacks run between them.
The async variants fix it. Vitest's docs say vi.advanceTimersByTimeAsync "will include asynchronously set timers": it lets promise callbacks run between timers. Each of advanceTimersByTime, advanceTimersToNextTimer, runAllTimers and runOnlyPendingTimers has an Async version. In a React test, wrap it in async act:
await act(async () => {
await vi.advanceTimersByTimeAsync(3000);
});user-event and Testing Library under fake timers
Both were built around Jest's fake timers, and that shows under Vitest:
- user-event pauses between inputs with
setTimeout(thedelayoption, 0 by default), and under fake timers nothing fires that timeout. Its docs say to pass your clock,userEvent.setup({ advanceTimers: vi.advanceTimersByTime }), and advise against the olderdelay: nullworkaround. - React Testing Library's async wrapper, which
waitFor,findByand user-event calls all go through, ends with a shortsetTimeoutthat it advances only when it detects Jest's fake timers. Under Vitest's fake timers these calls can hang until the test times out, even withadvanceTimersset. It is an open issue in the React Testing Library repository.
The dependable pattern: keep tests that need fake timers synchronous, with fireEvent for the interaction, act(() => { vi.advanceTimersByTime(...); }) to move time and getBy to assert. Give tests that need user-event and findBy real timers. vi.useFakeTimers({ shouldAdvanceTime: true }) also unblocks them, but then real time leaks into the fake clock. Vitest's own vi.waitFor, vi.waitUntil and expect.poll do advance fake timers while they wait.
Turn fake timers on before the code under test schedules anything, usually before render. A timer created with the real setTimeout stays real.
Why tests flake
eyni kod üzərində gah keçir, gah düşür. Martin Fowler deterministik olmayan testləri faydasız və "bütün test dəstini tamamilə məhv edə bilən, sürətlə yayılan infeksiya" adlandırır: insanlar qırmızının bəzən heç nə demədiyini öyrənəndə uğursuzluqları oxumaq əvəzinə yenidən işə salırlar və real bug-lar keçib gedir.
Testin nəticəsi onun idarə etmədiyi nədənsə asılı olanda test flaky olur. Ən çox rast gəlinən səbəblər:
- Vaxt. Sabit sleep-lər, asinxron iş bitməmiş işləyən assertion-lar, noutbuka uyğun gələn, yüklü CI maşınına isə çatmayan timeout-lar, hələ davam edən animasiyalar.
- Testlər arasında paylaşılan state. Vitest hər test faylına ayrıca mühit verir, faylın içindəki testlər isə bir-birinin ardınca işləyir və modul state-ini, cleanup yoxdursa DOM-u,
restoreMocksvə ya əl ilə bərpa onları sıfırlamırsa mock-ları, stub edilmiş qlobal dəyişənləri və brauzer yaddaşını paylaşır. - Sıradan asılılıq. Test yalnız ona lazım olan məlumatı əvvəlki test yaratdığı üçün keçir, ya da arxasında nəsə qoyub gedən testdən sonra düşür.
- Real şəbəkə. Cavablar yavaş gəlir, serverlər işləmir, rate limit-lər işə düşür, məlumat dəyişir.
- Təsadüfilik.
Math.random(), generasiya olunan id-lər, sabit seed-i olmayan təsadüfi test datası. - Tarixlər və saat qurşaqları. "Bu gün", ayın sonu, yay vaxtına keçid, maşının saat qurşağı.
- Sızmalar. Bir testin taymeri və ya sorğusu növbəti testin vaxtında işə düşür.
- Paylaşılan resurslar. Paralel işləyən fayllar eyni port-dan, fayldan və ya verilənlər bazasından istifadə edir.
Saat qurşağından yaranan flaky test
export function formatDueDate(iso: string) {
return new Date(iso).toLocaleDateString("en-GB");
}
test("formats the due date", () => {
expect(formatDueDate("2026-03-01T22:30:00Z")).toBe("02/03/2026");
});Bakıdakı noutbukda (UTC+4) bu an 2 martın 02:30-udur və test keçir. UTC-də işləyən CI runner-ində isə bu, 1 martın 22:30-udur, funksiya "01/03/2026" qaytarır və test düşür. Heç kim kodu dəyişməyib. Düzəliş məhsul qərarı ilə başlayır: son tarix hansı saat qurşağına aiddir? Sonra onu açıq şəkildə ötür, toLocaleDateString("en-GB", { timeZone: "Asia/Baku" }), və nəticə artıq maşından asılı olmur. Test dəstini sabit TZ ilə işə salmaq bütün maşınlarda eyni nəticə verir, amma başqa saat qurşaqlarındakı real istifadəçilərin görəcəyi bug-ları da gizlədir.
Hər flaky test testin günahı deyil
Bəzən test düzdür, məhsulda isə race var: ikiqat göndərmə, unmount-dan sonra işləyən effekt, istənilən sırada bitə bilən iki sorğu. Testi flaky adlandırmazdan əvvəl yoxla ki, uğursuz nəticə istifadəçinin də başına gələ bilməz.
A passes and fails on the same code. Martin Fowler calls non-deterministic tests useless and "a virulent infection that can completely ruin your entire test suite": once people learn that red sometimes means nothing, they rerun failures instead of reading them, and real bugs get through.
A test flakes when its result depends on something it does not control. The usual suspects:
- Timing. Fixed sleeps, assertions that run before async work finishes, timeouts that fit a laptop but not a busy CI machine, animations still running.
- State shared between tests. Vitest gives each test file its own environment, and tests inside a file run one after another, sharing module state, the DOM if cleanup is missing, mocks unless
restoreMocksor manual restores reset them, stubbed globals and browser storage. - Order dependence. A test passes only because an earlier one created the data it needs, or fails only after one that leaves something behind.
- The real network. Responses are slow, servers are down, rate limits kick in, data changes.
- Randomness.
Math.random(), generated ids, random test data without a fixed seed. - Dates and time zones. "Today", the end of the month, daylight saving time, the machine's time zone.
- Leaks. A timer or request from one test fires during the next.
- Shared resources. Files running in parallel use the same port, file or database.
A time zone flake
export function formatDueDate(iso: string) {
return new Date(iso).toLocaleDateString("en-GB");
}
test("formats the due date", () => {
expect(formatDueDate("2026-03-01T22:30:00Z")).toBe("02/03/2026");
});On a laptop in Baku (UTC+4) the instant is 02:30 on 2 March, and the test passes. On a CI runner in UTC it is 22:30 on 1 March, the function returns "01/03/2026", and the test fails. Nobody changed any code. The fix starts with a product decision: which zone does the due date belong to? Then pass it explicitly, toLocaleDateString("en-GB", { timeZone: "Asia/Baku" }), and the result no longer depends on the machine. Running the suite with a fixed TZ makes every machine agree, but it also hides bugs that real users in other zones would see.
Not every flake is the test's fault
Sometimes the test is right and the product has a race: a double submit, an effect that runs after unmount, two requests that finish in either order. Before calling a test flaky, check that the failing result could not happen to a user.
Finding a flaky test
CI-dakı flaky uğursuzluğu təkrarlaya bilmirsənsə, onu debug etmək çətindir. Əvvəlcə onu istədiyin vaxt düşməyə məcbur et.
Testi dəfələrlə işə sal
vitest run src/cart.test.ts --repeats=50--repeats hər testi göstərilən sayda əlavə dəfə işə salır, istənilən təkrarın düşməsi isə testi uğursuz edir. Debug edərkən bir test də öz seçimlərində { repeats: 50 } təyin edə bilər. 50 dəfədən 2-sində düşən test artıq üzərində işləyə biləcəyin bir şeydir.
Sıranı dəyiş
vitest run --sequence.shuffle
vitest run --sequence.shuffle --sequence.seed=1234Shuffle faylları və testləri təsadüfi sırada işə salır və başqa testin əvvəl işləməsindən asılı olan testləri üzə çıxarır. Sıranı seed müəyyən edir. Öz seed-ini ötür və run-lar arasında onu dəyiş; hansısa düşəndə, düzəldərkən həmin sıranı təkrarlamaq üçün eyni seed ilə yenidən işə sal.
İki sürətli eksperiment axtarış dairəsini daraldır:
- Testi tək işə sal:
-t "adds an item". Tək keçir, faylla birlikdə düşürsə, başqa test arxasında state qoyur. Tək düşür, faylda keçirsə, test əvvəlki testin qurduğu nədənsə asılıdır. - Onu qonşuları ilə başqa sırada işə sal, sonra günahkar aydın olana qədər faylı yarıya böl.
CI şəraitini yenidən yarat
- Saat qurşağı və saat:
TZ=UTC vitest run, ayın sonu kimi tarix halları üçün isəvi.setSystemTime. - Yük: CI maşınları daha yavaşdır və çoxlu worker işlədir. Paralel faylların paylaşılan resurs üstündə toqquşub-toqquşmadığını görmək üçün daha az worker və ya
--no-file-parallelismsına, vaxtla bağlı fərziyyələri üzə çıxarmaq üçün isə yüklü maşında işə sal. - Sızmalar:
--detectAsyncLeakstest faylının işlək qoyub getdiyi taymerləri və digər asinxron resursları bildirir. Testləri xeyli yavaşladır, ona görə yalnız debug zamanı işlət.
Sübutları oxu
Uğursuzluğun əslində nə dediyinə bax: hansı assertion, hansı dəyər, hansı vaxt. Bir neçə uğursuz run-ı müqayisə et. Uğursuzluq həmişə eyni səhv dəyəri göstərirsə, state-ə və ya məlumata bax; "Unable to find" və ya timeout göstərirsə, vaxta bax. Run-lar arasında təkrarlanan qanunauyğunluq çox vaxt səbəbi kodu oxumaqdan daha tez göstərir.
A flaky failure in CI is hard to debug if you cannot reproduce it. Make it fail on demand first.
Run it many times
vitest run src/cart.test.ts --repeats=50--repeats runs every test that many extra times, and a failure in any run fails the test. One test can also set { repeats: 50 } in its options while you debug it. A test that fails 2 times out of 50 is now something you can work on.
Change the order
vitest run --sequence.shuffle
vitest run --sequence.shuffle --sequence.seed=1234Shuffling runs files and tests in random order, which exposes tests that depend on another test running first. The seed decides the order. Pass your own seed and change it between runs; when one fails, run again with the same seed to replay that order while you fix it.
Two quick experiments narrow it down:
- Run the test alone with
-t "adds an item". If it passes alone but fails with its file, another test leaves state behind. If it fails alone but passes in the file, it depends on something an earlier test set up. - Run it with its neighbours in a different order, then halve the file until the culprit is clear.
Recreate CI conditions
- Time zone and clock:
TZ=UTC vitest run, andvi.setSystemTimefor date edge cases such as month ends. - Load: CI machines are slower and run many workers. Try fewer workers or
--no-file-parallelismto see if parallel files fight over a shared resource, and a loaded machine to expose timing assumptions. - Leaks:
--detectAsyncLeaksreports timers and other async resources a test file left running. It makes tests much slower, so use it only while debugging.
Read the evidence
Look at what the failure actually says: which assertion, which value, at what time. Compare several failing runs. If the failure always shows the same wrong value, look for state or data; if it shows "Unable to find" or a timeout, look for timing. A pattern across runs often points at the cause faster than reading the code.
Fixing flaky tests instead of retrying them
Səbəbi biləndə düzəliş adətən mexaniki olur:
| Səbəb | Düzəliş |
|---|---|
| Sabit sleep, vaxtından əvvəl assertion | Şərti gözlə: findBy, waitFor, expect.poll |
| Başqa testdən qalmış state | beforeEach/afterEach-də sıfırla; restoreMocks, unstubGlobals, cleanup; hər test üçün təzə məlumat |
| Real şəbəkə | Onu şəbəkə və ya modul səviyyəsində mock et |
| Saat və saat qurşağı | vi.setSystemTime; kodda açıq timeZone |
| Təsadüfilik | Generatoru inject et və ya seed ver; dəqiq dəyərləri yox, xassələri yoxla |
| Sızan taymerlər və ya sorğular | Kodu düzəlt: cleanup zamanı taymerləri təmizlə, sorğuları abort et |
Hər düzəliş testi əvvəllər asılı olduğu nəyisə idarə etməyə məcbur edir. Səbəb məhsuldakı race çıxsa, məhsulu düzəlt; test haqlı idi.
Retry son çarədir
export default defineConfig({
test: { retry: 3 },
});Qlobal retry qırmızı build-ləri yaşıla çevirir və heç nə öyrətmir. Real race-ləri səndən gizlədir, istifadəçilər isə onlarla yenə qarşılaşır; düşən test dəstlərini yavaşladır, təkrar işə salınan hər test də vaxt aparır. Nəzarətindən kənarda olan nəsə həqiqətən etibarsızdırsa, məsələn end-to-end run-dakı xarici servis, retry-ı yalnız onunla məhdudlaşdır. retry count, delay və condition regex-i olan obyekt də ola bilər, onda yalnız uyğun gələn xətalar təkrarlanır:
retry: { count: 2, condition: /ECONNREFUSED/ }Karantin
Martin Fowler deterministik olmayan testləri əsas pipeline-dan kənara, karantinə çıxarmağı, "amma karantindəki testləri tez düzəltməyi" məsləhət görür. O, limit də təklif edir, məsələn az sayda test və ya ən çoxu bir həftə, ki karantin qəbiristanlığa çevrilməsin. Vitest-in test tag-ları bunun sadə yolunu verir: testi config-də təyin olunmuş flaky tag-ı ilə işarələ və əsas test dəstini vitest --tags-filter="!flaky" ilə işə sal.
test("syncs the cart", { tags: ["flaky"] }, async () => {
// ...
});Adi test.skip də işləyir, əgər onun yanında əlaqəli issue və sahibi varsa. Hər iki halda karantindəki test test etməkdən imtina qərarı yox, son tarixi olan məlum bug-dır.
Once you know the cause, the fix is usually mechanical:
| Cause | Fix |
|---|---|
| Fixed sleep, assertion too early | Wait for a condition: findBy, waitFor, expect.poll |
| State left by another test | Reset in beforeEach/afterEach; restoreMocks, unstubGlobals, cleanup; fresh data per test |
| Real network | Mock it at the network or module level |
| Clock and time zone | vi.setSystemTime; an explicit timeZone in the code |
| Randomness | Inject or seed the generator; assert on properties, not exact values |
| Leaked timers or requests | Fix the code: clear timers and abort requests on cleanup |
Each fix makes the test control something it used to depend on. If the cause turns out to be a race in the product, fix the product; the test was right.
Retries are a last resort
export default defineConfig({
test: { retry: 3 },
});A global retry turns red builds green and teaches nothing. It hides real races from you while users still meet them, makes failing suites slower, and every retried test still costs time. If something outside your control really is unreliable, such as an external service in an end-to-end run, limit the retry to it. retry can also be an object with count, delay and a condition regex, so only matching errors are retried:
retry: { count: 2, condition: /ECONNREFUSED/ }Quarantine
Martin Fowler's advice is to move non-deterministic tests to a quarantine, out of the main pipeline, "but fix quarantined tests quickly". He suggests a limit, such as a small number of tests or a week at most, so quarantine does not become a graveyard. Vitest's test tags give you a simple way: mark the test with a flaky tag defined in the config, and run the main suite with vitest --tags-filter="!flaky".
test("syncs the cart", { tags: ["flaky"] }, async () => {
// ...
});A plain test.skip works too, if it comes with a linked issue and an owner. Either way, a quarantined test is a known bug with a deadline, not a decision to stop testing.
Interview tips
30 saniyəlik cavab. "Asinxron test yoxladığı işi gözləməlidir: hər şeyi await et, sleep əvəzinə findBy və ya waitFor işlət, waitFor-a isə heç vaxt yan təsir qoyma. act xəbərdarlığı testin gözləmədiyi state yenilənməsinin baş verdiyini bildirir. Fake timer-lər vaxtdan asılı kodu sürətli və deterministik edir, amma promise-lər olanda async variantlar lazımdır. Flaky testlər vaxtdan, paylaşılan state-dən, sıradan, şəbəkədən, təsadüfilikdən və saatdan yaranır. Onları repeats və qarışdırılmış sıra ilə təkrarlayıram, səbəbi düzəldirəm, retry və karantini isə yalnız qısamüddətli tədbir kimi işlədirəm."
Gözlənilən suallar
- Kod pozuq olduğu halda bu test niyə keçir? Heç kimin await etmədiyi və ya qaytarmadığı promise; düzəlişi və
expect.hasAssertions()-ı göstər. waitFornecə işləyir? Callback-i dərhal, sonra hər 50 ms-dən bir və DOM dəyişəndə işə salır, bu, xəta atmağı dayandırana və ya 1000 ms keçənə qədər davam edir; təkrar cəhd üçün callback xəta atmalıdır.- act xəbərdarlığı nə deməkdir və onu necə düzəldirsən? Heç bir
act-in əhatə etmədiyi yenilənmə; hər şeyin ətrafınaactqoymaq əvəzinə nəticədə yaranan UI-ıfindByilə gözlə. - 5 saniyəlik timeout-u necə test edirsən? Fake timer-lər, 4999 və 5000 ms-ə qədər irəli çək, hər iki tərəfi yoxla.
- Test CI-da 20 run-dan birində düşür. Nə edirsən?
--repeatsvə--sequence.shuffleilə təkrarla, tək işə sal, CI-ın saat qurşağını və yükünü təkrarla, sonra səbəbi düzəlt. - Retry-ları yandıraq? Qlobal yox; onların nəyi gizlətdiyini və dar retry-ın nə vaxt məqbul olduğunu izah et.
Bal itirməyə səbəb olan səhvlər
- İlk fikir kimi "1000 ms-lik
setTimeoutəlavə et" və ya "timeout-u artır" demək. - Xəbərdarlığı susdurmaq üçün hər şeyi
act-ə bükmək. advanceTimersByTime-ınawait-dən sonrakı kodu niyə işə salmadığını bilməmək.- Flaky olmanı testdəki və ya məhsuldakı bug yox, bədbəxt təsadüf saymaq.
Senior səviyyəni göstərən məqamlar
Test dəstindən sistem kimi danış. Flaky olmanı yaddaşla yox, CI tarixçəsi ilə ölç. Əsas branch-ı etibarlı saxla: sahibi və son tarixi olan karantin, asılı qalan promise-ləri və await olunmamış query-ləri tutan lint ayarları, config-də cleanup və restoreMocks, məlum saat qurşağında işləyən CI. Bunu da qeyd et ki, bəzi flaky testlər yalnız build üçün yox, istifadəçilər üçün də düzəltməyə dəyən məhsul race-ləridir.
A 30-second answer. "An async test must wait for the work it checks: await everything, use findBy or waitFor instead of sleeps, and never put side effects in waitFor. The act warning means a state update happened that the test did not wait for. Fake timers make time-based code fast and deterministic, but with promises you need the async variants. Flaky tests come from timing, shared state, order, the network, randomness and the clock. I reproduce them with repeats and shuffled order, fix the cause, and use retries or quarantine only as a short-term measure."
Questions you are likely to get
- Why does this test pass when the code is broken? A promise nobody awaits or returns; show the fix and
expect.hasAssertions(). - How does
waitForwork? Runs the callback at once, then every 50 ms and on DOM changes, until it stops throwing or 1000 ms pass; the callback must throw to be retried. - What does the act warning mean and how do you fix it? An update outside any
actscope; wait for the resulting UI withfindByinstead of addingactaround everything. - How do you test a 5-second timeout? Fake timers, advance to 4999 and 5000 ms, assert both sides.
- A test fails once in 20 CI runs. What do you do? Reproduce with
--repeatsand--sequence.shuffle, run it alone, match CI's time zone and load, then fix the cause. - Should we turn on retries? Not globally; explain what they hide and when a narrow retry is acceptable.
Mistakes that cost points
- "Add a
setTimeoutof 1000 ms" or "increase the timeout" as the first idea. - Wrapping everything in
actto silence the warning. - Not knowing why
advanceTimersByTimedoes not run code after anawait. - Treating flakiness as bad luck rather than a bug in the test or the product.
Senior signal
Talk about the suite as a system. Measure flakiness from CI history, not memory. Make the main branch stay trustworthy: quarantine with an owner and a deadline, a lint setup that catches floating promises and un-awaited queries, cleanup and restoreMocks in config, CI that runs in a known time zone. And point out that some flakes are product races worth fixing for users, not just for the build.
What to check when reviewing async tests
Yazmadığın asinxron testləri (komanda yoldaşının pull request-ini, kitabxananın nümunəsini, AI assistentin təklifini) review edəndə bu siyahıdan istifadə et. Düzgün gözləməyən asinxron test ya heç nəyi yoxlamadan keçir, ya da təsadüfi düşür və hər ikisi sonradan indi qənaət etdiyindən baha başa gəlir.
- Hər promise await olunub və ya qaytarılıbmı?
return-süz.then(-ə,await-sizuser.vəfindByçağırışlarına vəawait-sizwaitFor-a bax. Test olunan kodu sil və testi işə sal: o, düşməlidir. - Test sabit vaxtı yox, şərti gözləyirmi? Testi keçirmək üçün
setTimeoutfasiləsi və ya artırılmış timeout testin kodla yarışdığını göstərir; əvəzindəfindBy,waitForvə yaexpect.pollolmalıdır. waitForyalnız assertion-lar üçün işlədilibmi? Callback-in içində klik, render və ya sorğu yoxdur, hər callback-də bir assertion var və boş callback heç vaxt yoxdur.- Fake timer-lər düzgün qurulub və söndürülübmü?
render-dən əvvəl yandırılıb,afterEach-də bərpa olunub, promise-lər olan yerdəAsyncvariantlar işlədilib və heç birfindBy,waitForvə ya user-event çağırışı Vitest-in saxta saatını gözləyib qalmır. - Hər test ona lazım olan state-i özü yaradırmı? Başqa testin məlumatına söykənmir; mock-lar, qlobal dəyişənlər və DOM testlər arasında sıfırlanır. Yoxlamaq üçün faylı
--sequence.shuffleilə işə sal. - Vaxt, saat qurşağı, təsadüfilik və şəbəkə testin nəzarətindədirmi?
vi.setSystemTime, açıqtimeZone, seed verilmiş və ya inject olunmuş təsadüfi mənbə, mock edilmiş sorğular. Komandan başqa saat qurşağında işləyirsə, testləri bir dəfəTZ=UTCilə işə sal. - Hər
retry-ın və yaskip-in səbəbi varmı? Dar şərt və ya sahibi olan əlaqəli issue; qlobalretryreal problemləri gizlədir.
Use this list on async tests you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. An async test that does not wait correctly either passes without checking anything or fails at random, and both cost more later than they save now.
- Is every promise awaited or returned? Look for
.then(withoutreturn,user.andfindBycalls withoutawait, andwaitForwithoutawait. Remove the code under test and run the test: it must fail. - Does the test wait for a condition, not a fixed time? A
setTimeoutpause or a raised timeout to make a test pass means it races the code; it should usefindBy,waitFororexpect.pollinstead. - Is
waitForused only for assertions? No clicks, renders or requests inside the callback, one assertion per callback, and never an empty callback. - Are fake timers set up and torn down correctly? Turned on before
render, restored inafterEach, theAsyncvariants used where promises are involved, and nofindBy,waitForor user-event call left waiting on Vitest's fake clock. - Does each test create the state it needs? No reliance on data from another test; mocks, globals and the DOM reset between tests. Run the file with
--sequence.shuffleto check. - Are time, time zone, randomness and the network under the test's control?
vi.setSystemTime, an explicittimeZone, a seeded or injected random source, mocked requests. Run once withTZ=UTCif your team works in another zone. - Does every
retryorskiphave a reason? A narrow condition or a linked issue with an owner; a globalretryhides real problems.