Nəyi və hansı səviyyədə test etməli
Testlər nə üçündür və onları hansı səviyyədə yazmalı: unit, inteqrasiya və end-to-end testlər və hər birinin qiyməti, test piramidası və testing trophy, implementasiya detallarının yox, davranışın yoxlanması, nəyi test etməməli, code coverage-in nəyi ölçdüyü, CI-da və code review-da reqressiya testləri.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
İlkin şərt yoxdur.
Bu mövzu Junior səviyyəsindən başlayır.
Testləri niyə yazırıq
Test sənin kodunun bir hissəsini işə salıb nəticəni avtomatik yoxlayan koddur. Onu bir dəfə yazırsan, Vitest kimi test runner isə hər dəyişiklikdən sonra onu yenidən, bir neçə saniyəyə və hər dəfə eyni qaydada işə salır.
import { expect, test } from "vitest";
import { cartTotal } from "./cart";
test("adds up price times quantity", () => {
const items = [
{ price: 4, quantity: 2 },
{ price: 10, quantity: 1 },
];
expect(cartTotal(items)).toBe(18);
});Bunu cart.ts-in yanında cart.test.ts adı ilə saxla, Vitest-i quraşdır (npm install -D vitest) və npx vitest əmrini işə sal. Vitest adı *.test.* və ya *.spec.* olan faylları tapır, onlardakı hər test-i işə salır və hansılarının uğursuz olduğunu bildirir. expect(value).toBe(18) assertion-dır: dəyər 18 deyilsə, xəta atır və test uğursuz olur. Öz kompüterində Vitest bundan sonra faylları izləməyə davam edir və faylı saxlayanda testləri yenidən işə salır; CI-da isə bir dəfə işləyib çıxır.
Testlər sənə nə verir
- Kodu dəyişməyə əminlik. Testlər olmadan hər refaktorinq, asılılığın yenilənməsi və ya bug düzəlişi tətbiqi əllə gəzib düzgün ekranları yoxladığına ümid etmək deməkdir. Testlər olanda isə runner bir neçə saniyəyə sənə deyir ki, vacib saydığın davranış hələ də qüvvədədirmi. Martin Fowler "testlər kifayətdirmi" sualına məhz belə cavab verir: bug-lar production-a nadir hallarda çatır və sən kodu dəyişməkdən nadir hallarda çəkinirsən.
- Davranışın spesifikasiyası. "adds up price times quantity" adı və onun nümunəsi xəbərsiz köhnələ bilməyən sənəddir: davranış dəyişsə, test uğursuz olur. Komandaya yeni gələn adam modulun nə vəd etdiyini test faylını oxuyaraq öyrənə bilər.
- Əllə yoxlamadan sürətli cavab. Unit test millisaniyələrlə işləyir. Eyni qaydanı brauzerdə yoxlamaq bir dəqiqə çəkir və heç kim bunu hər dəyişiklikdən sonra hər kənar hal üçün etmir.
- Dizayn haqqında siqnal. Saatı oxuyan, şəbəkəyə müraciət edən və qiyməti hesablayan, hamısını bir yerdə edən funksiyanı test etmək çətindir, təkrar istifadə etmək də. Test yazmaq bunu erkən göstərir.
Testlər nəyi vermir
Testlər yalnız yazdığın halların gözlədiyin kimi işlədiyini göstərir; kodda bug olmadığını sübut etmir. Səhv şeyi yoxlayan, ya da heç nəyi yoxlamayan test də yaxşı test qədər yaşıl görünür. Test yalnız assertion (və ya başqa nəsə) xəta atanda uğursuz olur, ona görə də heç bir assertion-ı olmayan test kod çökmədikcə keçir. Bu mövzunun qalan hissəsi də buna görə neçə test yazmaq haqqında yox, hansı testləri və harada yazmaq haqqındadır.
A test is code that runs a piece of your code and checks the result automatically. You write it once, and a test runner such as Vitest runs it again after every change, in seconds, the same way every time.
import { expect, test } from "vitest";
import { cartTotal } from "./cart";
test("adds up price times quantity", () => {
const items = [
{ price: 4, quantity: 2 },
{ price: 10, quantity: 1 },
];
expect(cartTotal(items)).toBe(18);
});Save it as cart.test.ts next to cart.ts, install Vitest (npm install -D vitest) and run npx vitest. Vitest finds files named *.test.* or *.spec.*, runs every test in them and reports which ones failed. expect(value).toBe(18) is an assertion: if the value is not 18, it throws, and the test fails. On your machine Vitest then keeps watching and reruns the tests when you save a file; in CI it runs once and exits.
What tests give you
- Confidence to change code. Without tests, every refactor, dependency upgrade or bug fix means clicking through the app by hand and hoping you checked the right screens. With tests, the runner tells you within seconds whether the behaviour you care about still holds. Martin Fowler's test for "enough tests" is exactly this: bugs rarely escape into production, and you are rarely afraid to change code.
- A specification of behaviour. "adds up price times quantity" plus its example is documentation that can't silently go out of date: if the behaviour changes, the test fails. A new teammate can read the test file to learn what the module promises.
- Faster feedback than checking by hand. A unit test runs in milliseconds. Checking the same rule in the browser takes a minute, and nobody does it for every edge case after every change.
- A signal about design. A function that reads the clock, calls the network and computes a price at once is hard to test, and just as hard to reuse. Writing the test shows that early.
What tests don't give you
Tests show that the cases you wrote behave as you expected; they don't prove the code has no bugs. A test that checks the wrong thing, or nothing at all, is just as green as a good one. A test fails only when an assertion (or anything else) throws, so a test with no assertions passes as long as the code doesn't crash. That is why the rest of this topic is about which tests to write and where, not about how many.
Unit, inteqrasiya və end-to-end testlər
Testlər sistemin nə qədərini bir anda işə saldıqlarına görə fərqlənir. Adətən üç səviyyədən danışılır:
- kiçik bir məntiq parçasını tək halda yoxlayır: funksiyanı, hook-u, reducer-i. Ucuz asılılıqlar (təmiz köməkçi funksiya) real qalır; yavaş və ya idarəolunmaz olanlar (şəbəkə, saat) əvəz olunur.
- bir neçə hissənin birlikdə işlədiyini yoxlayır: validasiyası və API client-i ilə birlikdə form, real uşaq komponentləri ilə birlikdə səhifə komponenti. Frontend-də bu, çox vaxt komponent ağacını simulyasiya olunmuş DOM-da render edib yalnız şəbəkəni əvəz etmək deməkdir.
- real, build olunmuş tətbiqi real brauzerdə, real və ya realistik backend ilə işə salır və istifadəçi kimi davranır: səhifəni açır, yazır, klikləyir, ekranda nə çıxdığını yoxlayır. Ən çox işlədilən alətlər Playwright və Cypress-dir.
| Unit | İnteqrasiya | End-to-end | |
|---|---|---|---|
| Adi işləmə müddəti | millisaniyələr | onlarla-yüzlərlə ms | saniyələr |
| Nəyi tutur | məntiq xətaları, kənar hallar | uyğun gəlməyən hissələr: props, sahə adları, çağırış sırası | sınıq routing, build, konfiqurasiya, yalnız brauzerdə olan bug-lar |
| Bug-ın yerini göstərir | dəqiq | təxminən | nadir hallarda |
| Koddan kənar səbəbə görə düşür | demək olar ki, heç vaxt | az-az | tez-tez: şəbəkə, test datası, vaxt |
Hər səviyyənin qiyməti
Sürət qiymətin yalnız bir hissəsidir. Yuxarı səviyyəli testlər daha yavaşdır və onları qurmaq daha çətindir, amma əsas qiymət səs-küydür: end-to-end test test serveri ləng cavab verdiyi, lazımi qeyd bazaya yazılmadığı və ya animasiya hələ bitmədiyi üçün də düşə bilər. Kodda heç nə dəyişmədən bəzən düşən test adlanır və hər belə test komandanı qırmızı build-lərə məhəl qoymamağa öyrədir.
Aşağı səviyyəli testlərin zəifliyi isə əksinədir: onlar sürətli və dəqiqdir, amma məhsul sınıq olduğu halda hamısı keçə bilər. Hər unit ayrılıqda düzgün ola bilər, iki unit isə bir-biri ilə razılaşmaya bilər: məsələn, form { qty } göndərir, API client isə quantity oxuyur. Bunu yalnız ikisini birlikdə işə salan test görür.
Eyni dəyişiklik səviyyələrə müxtəlif cür təsir edir: daxili köməkçi funksiyanın adını dəyiş, onu çağıran unit testlər sınır, end-to-end testlər isə heç nə hiss etmir; checkout düyməsinin bağlantısını qır, bütün unit testlər yaşıl qalır. Yaxşı test dəstində səviyyələr qarışıq olur ki, hər növ səhvi ən azı bir test, mümkün qədər ucuz başa gələrək tutsun.
Bu adlar dəqiq deyil. "Unit"-in bir funksiya, yoxsa köməkçiləri ilə birlikdə bir modul olması komandadan komandaya dəyişir; Martin Fowler bunu "situasiyadan asılı şey" adlandırır. Vacib olan komandanın bu barədə razılaşmasıdır.
Tests differ in how much of the system they run at once. The usual names are three levels:
- A checks one small piece of logic on its own: a function, a hook, a reducer. Cheap collaborators (a pure helper) stay real; slow or uncontrollable ones (the network, the clock) are replaced.
- An checks that several pieces work together: a form with its validation and its API client, a page component with its real children. In frontend work this often means rendering a component tree in a simulated DOM and replacing only the network.
- An runs the real, built app in a real browser against a real or realistic backend, and acts like a user: open the page, type, click, check what appears. Playwright and Cypress are the common tools.
| Unit | Integration | End-to-end | |
|---|---|---|---|
| Typical run time | milliseconds | tens to hundreds of ms | seconds |
| Catches | logic errors, edge cases | parts that disagree: props, field names, call order | broken routing, build, config, browser-only bugs |
| Points to the bug | precisely | roughly | rarely |
| Fails for reasons outside your code | almost never | seldom | often: network, test data, timing |
What each level costs
Speed is only part of the price. Higher-level tests are slower and harder to set up, but the bigger cost is noise: an end-to-end test can fail because a test server was slow, a seeded record was missing or an animation was still running. A test that sometimes fails without any change to the code is a , and every one teaches the team to ignore red builds.
Lower-level tests have the opposite weakness: they are fast and precise, but they can all pass while the product is broken. Each unit can be correct on its own while two of them disagree, for example the form sends { qty } and the API client reads quantity. Only a test that runs both together notices.
The same change hits the levels differently: rename an internal helper, and the unit tests that call it break while end-to-end tests don't notice; break the checkout button's wiring, and every unit test stays green. A good suite mixes levels so that each kind of mistake is caught by at least one test, as cheaply as possible.
The names are not precise. Whether a "unit" is one function or a module with its helpers differs between teams; Martin Fowler calls it "a situational thing". What matters is that a team agrees.
Arrange, act, assert
Yaxşı testlərin çoxu eyni üç addımdan ibarətdir. Bill Wake onları Arrange, Act, Assert (hazırla, icra et, yoxla) adlandırıb:
import { describe, expect, test } from "vitest";
import { applyCoupon } from "./coupon";
describe("applyCoupon", () => {
test("takes 10% off with SAVE10", () => {
// Arrange: giriş datası
const order = { subtotal: 200, coupon: "SAVE10" };
// Act: test olunan koda bir çağırış
const result = applyCoupon(order);
// Assert: çağıranın gördüyü nəticə
expect(result.total).toBe(180);
});
test("rejects an expired coupon", () => {
const order = { subtotal: 200, coupon: "SUMMER23" };
expect(() => applyCoupon(order)).toThrow("Coupon has expired");
});
});- Arrange vəziyyəti qurur: giriş datası, test datası, asılılıqların əvəzediciləri.
- Act bir iş görür: funksiyanı çağırır, action göndərir, düyməni klikləyir.
- Assert çağıranın görə bildiyi nəticəni yoxlayır: qaytarılan dəyəri, xətanı, ekrandakını, göndərilən sorğunu.
Behaviour-Driven Development eyni formanı Given, When, Then adları ilə işlədir (Daniel Terhorst-North və Chris Matts), Gerard Meszaros isə onu Four-Phase Test adlandırır və dördüncü addım, təmizləmə (teardown) əlavə edir. Martin Fowler bunları eyni şablon kimi təsvir edir.
Adlar
Testin adı bir davranışı ifadə edir ki, uğursuzluq pozulmuş vəd kimi oxunsun: applyCoupon > rejects an expired coupon. Kodu təsvir edən (calls validateDate) və ya heç nə deməyən (works, test 2) adlardan qaç. Ada "and" (və) lazım olursa, çox güman ki, bunlar iki ayrı testdir.
Testləri dürüst saxlayan vərdişlər
- Uğursuzluğun bir səbəbi. Bir nəticəni təsvir edirlərsə, bir neçə
expectnormaldır: məsələn, eyni sifarişin cəmi və endirim sətri. On əlaqəsiz şeyi yoxlayan test on səbəbdən düşür və onun adı bunların hamısını təsvir edə bilmir. - Gözlənilən dəyərlər hazır yazılsın.
toBe(200 - 200 * 0.1)və ya kodun özünün işlətdiyi köməkçi funksiyaya çağırış yox,toBe(180)yaz: cavabı kodla eyni yolla hesablayan test bug-ı da təkrarlayır. - Testdə məntiq olmasın. Test gövdəsindəki dövrlər və
if-lər onu səhv ola bilən ikinci proqrama çevirir. Bir-birinə oxşar çoxlu hal üçüntest.eachilə giriş cədvəlindən istifadə et. - Bir dəfə düşdüyünü gör. Yeni testə etibar etməzdən əvvəl kodu qəsdən sındır və ya testi düzəlişdən əvvəl işə sal və onun qırmızı olduğunu gör. Heç vaxt düşməmiş test, ola bilsin, heç nəyi yoxlamır.
Most good tests have the same three steps, which Bill Wake named Arrange, Act, Assert:
import { describe, expect, test } from "vitest";
import { applyCoupon } from "./coupon";
describe("applyCoupon", () => {
test("takes 10% off with SAVE10", () => {
// Arrange: the input
const order = { subtotal: 200, coupon: "SAVE10" };
// Act: one call to the code under test
const result = applyCoupon(order);
// Assert: the result the caller sees
expect(result.total).toBe(180);
});
test("rejects an expired coupon", () => {
const order = { subtotal: 200, coupon: "SUMMER23" };
expect(() => applyCoupon(order)).toThrow("Coupon has expired");
});
});- Arrange builds the situation: inputs, test data, replacements for dependencies.
- Act does one thing: calls the function, dispatches the action, clicks the button.
- Assert checks what the caller can observe: a return value, an error, what is on the screen, what was sent.
Behaviour-Driven Development uses the same shape under the names Given, When, Then (from Daniel Terhorst-North and Chris Matts), and Gerard Meszaros calls it the Four-Phase Test, with a fourth step, teardown, that cleans up. Martin Fowler describes them as the same pattern.
Names
A test name states one behaviour, so that a failure reads like a broken promise: applyCoupon > rejects an expired coupon. Avoid names that describe the code (calls validateDate) or say nothing (works, test 2). If a name needs "and", it is probably two tests.
Habits that keep tests honest
- One reason to fail. Several
expectcalls are fine when they describe one outcome, such as the total and the discount line of the same order. A test that checks ten unrelated things fails for ten reasons, and its name can't describe them. - Literal expected values. Write
toBe(180), nottoBe(200 - 200 * 0.1)or a call to the helper the code itself uses: a test that computes the answer the same way repeats the bug. - No logic in the test. Loops and
ifin a test body make it a second program that can be wrong. For many similar cases, use a table of inputs withtest.each. - See it fail once. Before you trust a new test, break the code on purpose, or run the test before the fix, and watch it go red. A test that has never failed may not be testing anything.
Test piramidası və testing trophy
Layihədə hər səviyyədən neçə test olmalıdır? İki məşhur model bu suala fərqli cavab verir. Hər ikisi qanun yox, investisiyanın gəlirliliyi barədə fikirdir.
Test piramidası. Mike Cohn "Test Automation Pyramid"-i Succeeding with Agile (2009) kitabında təsvir edib, Martin Fowler-in bu barədə məqaləsi (2012) isə əsaslandırmanı verir: əsasda çoxlu sürətli unit test, ortada servis qatı üzərindən daha az test, zirvədə çox az UI testi, çünki UI üzərindən başdan-sona işləyən testlər "kövrək, yazılması baha və işləməsi uzun" olur. Ham Vocke-nin The Practical Test Pyramid məqaləsi (martinfowler.com, 2018) bunu iki qaydada ümumiləşdirir: müxtəlif detallıqda testlər yaz, səviyyə yüksəldikcə testlər azalmalıdır.
Testing trophy. Kent C. Dodds "Testing Trophy"-ni JavaScript tətbiqləri üçün çəkib (2018): ən aşağıda statik analiz, sonra unit, ən böyük hissə kimi inteqrasiya, ən yuxarıda end-to-end. Onun fikrincə, inteqrasiya testləri "əminlik ilə sürət/xərc arasındakı kompromisdə əla balans yaradır", ona görə səyin çoxu (hamısı yox) ora getməlidir. Bunun arxasında onun prinsipi dayanır, bu, həm də Testing Library-nin əsas prinsipidir: "Testlər proqramın necə istifadə olunduğuna nə qədər çox bənzəsə, sənə bir o qədər çox əminlik verə bilər."
pyramid (Cohn) trophy (Dodds)
fewest UI / E2E end-to-end
service integration (most effort)
most unit unit
underneath - static: types, lintStatik analiz təməldir. Dodds onu ona görə əlavə edib ki, JavaScript-də statik analiz öz-özünə mövcud deyil; o, "kodu yazdığın anda yazı və tip xətalarını tutur". Strict TypeScript və ESLint heç bir test işləməmişdən əvvəl hər sətri demək olar ki, pulsuz yoxlayır. Testləri tip yoxlayıcısının sübut etdiyinə (cartTotal-ın ədəd qaytardığına) xərcləmə; tiplərin görə bilmədiyinə (onun düzgün ədəd qaytardığına) xərclə.
Modellərin razılaşdığı yerlər
Fowler qeyd edib (2021) ki, mübahisənin çox hissəsi "unit test"-in nə demək olduğu üstündədir. Komponenti real uşaqları ilə render edən test bəziləri üçün sociable unit testdir (Jay Fields-in termini; asılılıqları double-larla əvəz edən solitary testin əksi), digərləri üçün isə inteqrasiya testi. Hər iki model razılaşır ki, testlərin çoxu sürətli və deterministik olmalıdır, end-to-end testlər ən baha növdür və vacib istifadəçi ssenarilərinə aiddir, test isə öz yerini yazılmasına, işləməsinə və saxlanmasına sərf olunan hər dəqiqəyə düşən əminliklə qazanır.
React tətbiqi üçün bu, belə deməkdir: komponentləri real uşaqları ilə render edib yalnız şəbəkəni saxtalaşdıran çoxlu sürətli test, ağır məntiq (parsing, qiymət, tarixlər) üçün unit testlər və heç vaxt sınmamalı olan axınlar üçün bir neçə end-to-end test.
How many tests of each level should a project have? Two well-known models answer differently. Both are opinions about return on investment, not laws.
The test pyramid. Mike Cohn described the "Test Automation Pyramid" in Succeeding with Agile (2009), and Martin Fowler's article on it (2012) gives the reasoning: many fast unit tests at the base, fewer tests through a service layer, very few UI tests at the top, because tests that run end-to-end through the UI are "brittle, expensive to write, and time consuming to run". Ham Vocke's The Practical Test Pyramid (martinfowler.com, 2018) sums it up in two rules: write tests with different granularity, and the more high-level you get, the fewer tests you should have.
The testing trophy. Kent C. Dodds drew the "Testing Trophy" for JavaScript applications (2018): static analysis at the bottom, then unit, integration as the biggest part, and end-to-end on top. Integration tests, he argues, "strike a great balance on the trade-offs between confidence and speed/expense", so most (not all) effort should go there. Behind it is his principle, which is also Testing Library's guiding principle: "The more your tests resemble the way your software is used, the more confidence they can give you."
pyramid (Cohn) trophy (Dodds)
fewest UI / E2E end-to-end
service integration (most effort)
most unit unit
underneath - static: types, lintStatic analysis is the base. Dodds added it because in JavaScript it is not a given; it catches "typos and type errors as you write the code". Strict TypeScript and ESLint check every line before any test runs, almost for free. Don't spend tests on what the type checker proves (that cartTotal returns a number); spend them on what types can't see (that it returns the right number).
Where the models agree
Fowler pointed out (2021) that much of the debate is about what "unit test" means. A test that renders a component with its real children is a sociable unit test to some (Jay Fields' term, the opposite of a solitary test that replaces collaborators with doubles) and an integration test to others. Both models agree that most tests should be fast and deterministic, that end-to-end tests are the most expensive kind and belong to the critical journeys, and that a test earns its place by the confidence it gives per minute spent writing, running and maintaining it.
For a React app this means many fast tests that render components with their real children and fake only the network, unit tests for heavy logic (parsing, pricing, dates), and a few end-to-end tests for flows that must never break.
İmplementasiya detallarını test etmək
Kent C. Dodds implementasiya detallarını belə tərif edir: "kodunun istifadəçilərinin adətən istifadə etmədiyi, görmədiyi, hətta bilmədiyi şeylər". Funksiyanın istifadəçiləri onu çağıranlardır. Komponentin isə iki istifadəçisi var: onu görüb klikləyən son istifadəçi və onu props ilə render edən developer. Bundan başqa hər hansı şeydən asılı olan testin iki problemi var və Dodds onları belə adlandırır:
- False negative (yalançı mənfi): kod hələ də işlədiyi halda test refaktorinqdən sonra düşür. İnsanlar yeni daxili quruluşu testə köçürərək "testi düzəltməyə" alışır və qırmızı nəticəyə etibar etməyi dayandırır.
- False positive (yalançı müsbət): kod sınıq olduğu halda test keçir, çünki o, nəticəni yox, daxili addımları yoxlayır.
// ✗ daxili state-i oxuyur
test("stores the item", () => {
const cart = createCart();
cart.add({ id: "tea", price: 4 });
expect(cart._items).toEqual([{ id: "tea", price: 4, quantity: 1 }]);
});
// ✓ public API-dən istifadə edir
test("counts a repeated item in the total", () => {
const cart = createCart();
cart.add({ id: "tea", price: 4 });
cart.add({ id: "tea", price: 4 });
expect(cart.count()).toBe(2);
expect(cart.total()).toBe(8);
});_items id açarı ilə saxlanan Map-ə çevrilsə, çağıranlar üçün heç nə dəyişməsə də, birinci test sınır. total() sınıq olanda isə o, keçməyə davam edir, çünki onu heç çağırmır. İkinci test daxili hissə yenidən yazılandan sonra da keçir və məhz çağıranın səhv rəqəm görəcəyi anda düşür.
Vitest bələdçisindən praktik yoxlama: kimsə daxili hissəni yenidən yazsa və nəticə eyni qalsa, bu test sınmalıdırmı? Sınacaqsa, o, implementasiya detalını yoxlayır.
Nəyə diqqət etməli
- private sahələrə, daxili state-ə və ya nəyinsə neçə dəfə render olunduğuna dair assertion-lar;
- kodun daxildə çağırdığı köməkçi funksiyanı yalnız çağırılıb-çağırılmadığını yoxlamaq üçün izləmək (spy);
- eyni feature-un öz modullarını mock etmək, nəticədə test nəticəni yox, bağlantıları təsvir edir;
- hər refaktorinqlə eyni commit-də dəyişən test faylı.
Private köməkçi funksiyanın ayrıca testlərə ehtiyacı varmış kimi görünürsə, Ham Vocke-nin məsləhətinə görə, çox güman ki, modul həddindən artıq çox iş görür: köməkçini öz public müqaviləsi olan modula çıxar və onu test et. React komponentləri üçün qayda belə səslənir: istifadəçi kimi qarşılıqlı əlaqəyə gir və state-i və ya uşaqların props-unu yox, ekranda olanı yoxla. Testing Library məhz bu ideya üzərində qurulub.
Amma hər nəticə qaytarılan dəyər deyil. onSave-i form dəyərləri ilə çağırmaq, analitika event-i göndərmək və ya storage-ə yazmaq çağıranların güvəndiyi şeydir və bunu test double ilə yoxlamaq davranışı test etməkdir. Sual budur: bu çağırış müqavilənin bir hissəsidir, yoxsa sadəcə nəticəyə çatmağın yollarından biri?
Kent C. Dodds defines implementation details as "things which users of your code will not typically use, see, or even know about". A function's users are its callers. A component has two: the end user who sees and clicks it, and the developer who renders it with props. A test that depends on anything else has two problems, which Dodds names:
- False negatives: it fails after a refactor although the code still works. People learn to "fix the test" by copying the new internals into it, and stop trusting a red result.
- False positives: it passes while the code is broken, because it checks internal steps instead of the result.
// ✗ reads internal state
test("stores the item", () => {
const cart = createCart();
cart.add({ id: "tea", price: 4 });
expect(cart._items).toEqual([{ id: "tea", price: 4, quantity: 1 }]);
});
// ✓ uses the public API
test("counts a repeated item in the total", () => {
const cart = createCart();
cart.add({ id: "tea", price: 4 });
cart.add({ id: "tea", price: 4 });
expect(cart.count()).toBe(2);
expect(cart.total()).toBe(8);
});If _items becomes a Map keyed by id, the first test breaks although nothing changed for callers. And it keeps passing if total() is broken, because it never calls it. The second test survives the rewrite and fails exactly when a caller would see a wrong number.
A practical check, from the Vitest guide: if someone rewrites the internals and the output stays the same, should this test break? If it would, it tests an implementation detail.
Signs to look for
- assertions on private fields, internal state, or how many times something rendered;
- spying on a helper that the code calls internally, only to check that it was called;
- mocking modules of the same feature, so the test describes the wiring instead of the result;
- a test file that changes in the same commit as every refactor.
If a private helper seems to need its own tests, Ham Vocke's advice is that the module probably does too much: move the helper into a module with its own public contract, and test that. For React components the rule reads: interact the way a user does and check what is on the screen, not state or props of children. Testing Library is built around this idea.
Not every outcome is a return value, though. Calling onSave with the form values, sending an analytics event or writing to storage is something callers rely on, and checking it with a test double is testing behaviour. The question is whether the call is part of the contract, or just one way of getting the result.
Nəyi test etməli, nəyi buraxmalı
Hər test yazılmağa, işləməyə və yenilənməyə vaxt aparır. Bu vaxtı bug-ların ehtimalı yüksək və baha başa gəldiyi yerlərə xərclə.
Test etməyə dəyər
- Budaqları olan məntiq: qiymətlər, endirimlər, icazələr, parsing, formatlama, validasiya qaydaları, reducer-lər, state maşınları.
- Sərhədlər: boş siyahı, sıfır, mənfi ədədlər, maksimal uzunluq, ayın son günü, çatışmayan optional sahə.
- Xəta yolları: yanlış giriş, reject olunmuş sorğu, timeout. Bunları heç kim əllə yoxlamır.
- Hissələr arasındakı müqavilələr: komponentin API client-ə göndərdiyi data forması, vidjetin göndərdiyi event-lər, hook-un qaytardığı dəyər.
- Əvvəllər sınmış hər şey. Bug kodun harada kövrək olduğunu göstərir, onun reqressiya testi isə onun geri qayıtmasının qarşısını alır.
Adətən ayrıca testə dəyməz
- Üçüncü tərəf kodu. React-in yenidən render etdiyini,
Array.prototype.sort-un sıraladığını və ya tarix kitabxanasının ISO sətirlərini parse etdiyini test etmə: bunu onların öz test dəstləri edir. Onlardan sənin necə istifadə etdiyini test et: cədvəlinin vəd etdiyi sıranı, funksiyanın verilmiş giriş üçün qaytardığı tarixi. - Trivial kod. Sahəni qaytaran getter, props-u sadəcə ötürən komponent, sabit. Ham Vocke-nin qaydası qısadır: "trivial kodu test etmirsən". Bu kod onu işlədən kodun testlərində onsuz da işləyir.
- Tip yoxlayıcısının onsuz da sübut etdiyi şeylər. Strict TypeScript arqumenti çatışmayan çağırışı qəbul etmirsə, həmin çağırışı yoxlayan test yalnız kompilyatoru yenidən test edir.
- Stillər və dəqiq markup. Class adları, rənglər və boşluqlar tez-tez dəyişir və davranış haqqında az şey deyir. jsdom kimi simulyasiya olunmuş DOM-lar ümumiyyətlə layout hesablamır (bunu onun README-si də deyir), ona görə elementin ekranda görünüb-görünmədiyini və ya başqası ilə örtülüb-örtülmədiyini bilə bilmir. Davranışı test et (deaktiv düymə, xəta mesajı), görünüşü isə real brauzerdəki screenshot testlərinə burax.
- Eyni qayda hər səviyyədə. Unit testlər bütün endirim qaydalarını əhatə edirsə, end-to-end checkout testinə on iki yox, bir kupon kifayətdir. Vocke-nin məsləhəti testləri piramidada bacardığın qədər aşağı salmaqdır.
Sürətli filtr
Test yazmazdan əvvəl iki sual ver. Bu davranış sınsa, istifadəçi və ya başqa developer bunu hiss edərmi? Bu test mənə bunu artıq olan testlərdən daha tez və ya daha dəqiq deyərmi? Hər iki cavab "yox"-dursa, test, çox güman ki, gətirdiyindən çox baha başa gəlir.
Əks səhv uğurlu ssenari (happy path) işlədiyi üçün xəta yolunu buraxmaqdır. Ekranda heç bir xəta mesajı göstərməyən reject olunmuş sorğu real bug-dır və onu yalnız test, ya da istifadəçi tapacaq.
Every test costs time to write, time to run and time to update. Spend them where bugs are likely and expensive.
Worth testing
- Logic with branches: pricing, discounts, permissions, parsing, formatting, validation rules, reducers, state machines.
- Boundaries: an empty list, zero, negative numbers, the maximum length, the last day of a month, a missing optional field.
- Error paths: invalid input, a rejected request, a timeout. Nobody clicks through these by hand.
- Contracts between parts: the shape a component sends to an API client, the events a widget emits, what a hook returns.
- Anything that broke before. A bug shows where the code is fragile, and its regression test stops it from coming back.
Usually not worth a test of its own
- Third-party code. Don't test that React re-renders, that
Array.prototype.sortsorts or that a date library parses ISO strings: their own test suites do that. Test your use of them: the order your table promises, the date your function returns for a given input. - Trivial code. A getter that returns a field, a component that only passes props through, a constant. Ham Vocke's rule is short: "you don't test trivial code". It still runs in the tests of the code that uses it.
- What the type checker already proves. If strict TypeScript rejects a call with a missing argument, a test that checks that call only re-tests the compiler.
- Styling and exact markup. Class names, colours and spacing change often and say little about behaviour. Simulated DOMs such as jsdom do no layout at all (its README says so), so they can't tell whether an element is visible on screen or covered by another. Test the behaviour (a disabled button, an error message), and leave the look to screenshot tests in a real browser.
- The same rule at every level. If unit tests cover every discount rule, the end-to-end checkout test needs one coupon, not twelve. Vocke's advice is to push tests as far down the pyramid as you can.
A quick filter
Before writing a test, ask two questions. If this behaviour broke, would a user or another developer notice? Would this test tell me sooner, or more precisely, than the tests I already have? If the answer to both is no, the test probably costs more than it returns.
The opposite mistake is skipping the error path because the happy path works. A rejected request with no visible error message is a real bug that only a test, or a user, will find.
Code coverage: nəyi ölçür və nəyi ölçmür
Coverage aləti testlər işlədiyi müddətdə kodunun hansı hissələrinin işlədiyini qeyd edir. Vitest onu vitest run --coverage ilə toplayır (standart olaraq v8 provayderi ilə, ya da istanbul ilə) və hər fayl üçün dörd rəqəm göstərir:
- statements və lines: onların neçəsi ən azı bir dəfə icra olunub;
- functions: neçə funksiya ən azı bir dəfə çağırılıb;
- branches:
if/else,? :,&&,||,??vəswitchüzərindən keçən yolların (budaqların) neçəsinə girilib.
Hesabatdan ən çox xəritə kimi faydalanırsan. Qırmızı sətirlər heç bir testin işə salmadığı koddur, çox vaxt da heç kimin ağlına gəlməyən xəta yoludur.
Coverage nəyi deyə bilmir
Coverage nəyin yoxlandığını yox, nəyin işlədiyini ölçür:
function shippingCost(total: number, country: string) {
if (country !== "AZ") return 15;
return total >= 50 ? 0 : 5;
}
test("shipping", () => {
shippingCost(10, "AZ");
shippingCost(60, "AZ");
shippingCost(60, "DE");
});Bu test sətirlərin, funksiyaların və budaqların 100%-ni əhatə edir, amma heç nə yoxlamır: bütün qaytarılan dəyərlər səhv olsa da, keçəcək. Martin Fowler bunun ifrat halını "AssertionFreeTesting" adlandırır. Yaxşı assertion-lar olsa belə, 100% branch coverage o demək deyil ki, şərtlərin bütün kombinasiyaları yoxlanılıb, sərhəd (cəmin düz 50 olması) yoxlanılıb və ya kod məhsula lazım olanı edir.
Fowler-in fikrincə, coverage "kod bazasının test olunmamış hissələrini tapmaq üçün faydalı alətdir", amma "testlərinin nə qədər yaxşı olduğunu göstərən rəqəm kimi az işə yarayır". Aşağı rəqəmlər, "təxminən yarıdan az", problem əlamətidir; yüksək rəqəmlər isə mütləq nəsə demək deyil. 100%-ə çox yaxın rəqəm onda metrikanı razı salmaq üçün yazılmış testlərə dair şübhə yaradardı. Kent C. Dodds da razıdır: təxminən 70%-dən sonra fayda azalır (bu rəqəmi uydurduğunu özü etiraf edir), tətbiq üçün 100% tələb etmək isə "çox pis ideyadır".
CI-da coverage
Vitest konfiqurasiyasındakı coverage.thresholds sətirlər, funksiyalar, budaqlar və statement-lər üçün minimal faizləri təyin edir; nəticə onlardan aşağı olanda run xəta ilə bitir və CI job-u düşür. Alt hədd kimi işlədiləndə threshold test olunmamış kod əlavə olunanda coverage-in səssizcə düşməsinin qarşısını alır. Məqsəd kimi işlədiləndə isə yuxarıdakı kimi testlərə yol açır. Fowler fərqi Brian Marick-in sözləri ilə göstərir: "I expect a high level of coverage. Sometimes managers require one. There's a subtle difference." (Mən yüksək coverage gözləyirəm. Bəzən menecerlər onu tələb edir. Fərq incədir.)
Review zamanı dəyişən sətirlərə bax: yeni budaq əhatə olunubmu və bu budaq səhv dəyər qaytarsa, düşəcək assertion varmı?
A coverage tool records which parts of your code ran while the tests were running. Vitest collects it with vitest run --coverage (with the v8 provider by default, or istanbul) and reports four numbers per file:
- statements and lines: how many executed at least once;
- functions: how many were called at least once;
- branches: how many paths through
if/else,? :,&&,||,??andswitchwere taken.
The report is most useful as a map. Red lines are code that no test ever ran, often an error path nobody thought about.
What coverage can't tell you
Coverage measures what ran, not what was checked:
function shippingCost(total: number, country: string) {
if (country !== "AZ") return 15;
return total >= 50 ? 0 : 5;
}
test("shipping", () => {
shippingCost(10, "AZ");
shippingCost(60, "AZ");
shippingCost(60, "DE");
});This test reaches 100% of lines, functions and branches, and asserts nothing: it passes even if every return value is wrong. Martin Fowler calls the extreme case "AssertionFreeTesting". Even with good assertions, 100% branch coverage doesn't mean every combination of conditions was tried, that the boundary (a total of exactly 50) was checked, or that the code does what the product needs.
Fowler's view is that coverage is "a useful tool for finding untested parts of a codebase" but "of little use as a numeric statement of how good your tests are". Low numbers, "say below half", are a sign of trouble; high numbers don't necessarily mean much. Anything close to 100% would make him suspicious of tests written to satisfy the metric. Kent C. Dodds agrees: returns diminish beyond about 70% (a number he admits is made up), and mandating 100% for an application is "a really bad idea".
Coverage in CI
coverage.thresholds in the Vitest config sets minimum percentages for lines, functions, branches and statements, and a run below them exits with an error, which fails the CI job. Used as a floor, a threshold stops coverage from quietly dropping when untested code is added. Used as a target, it invites tests like the one above. Fowler quotes Brian Marick on the difference: "I expect a high level of coverage. Sometimes managers require one. There's a subtle difference."
In review, look at the changed lines: is the new branch covered, and is there an assertion that would fail if that branch returned the wrong value?
CI-da və code review-da testlər
Testlər kod bazasını yalnız o halda qoruyur ki, hər dəyişiklikdə işə salınsınlar və onlar düşən halda heç nə merge olunmasın. Pull request üçün pipeline əvvəlcə ən ucuz yoxlamaları işə salır ki, yazı xətası uzun brauzer run-ından sonra yox, bir neçə saniyəyə üzə çıxsın:
npx tsc --noEmit
npx eslint .
npx vitest run --coverage
npx playwright testDeveloper-in kompüterində vitest watch rejimində başlayır, CI-da isə (process.env.CI təyin olunanda) və ya interaktiv olmayan terminalda bir dəfə işləyir. Review üçün CI-ın iki standart davranışı vacibdir. Vitest CI-da snapshot yazmır: çatışmayan, dəyişmiş və ya köhnəlmiş snapshot qeyd olunmaq əvəzinə run-ı uğursuz edir, ona görə snapshot yalnız kimsə onu lokal yeniləyib diff-i commit edəndə dəyişir. allowOnly isə CI-da söndürülüb, ona görə unudulmuş test.only qalan bütün testləri səssizcə ötürmək əvəzinə test dəstini uğursuz edir.
Test dəstini sürətli və etibarlı saxla
- Vaxt büdcəsi. Fowler Kent Beck-in təcrübi qaydasını xatırladır: commit zamanı işləyən test dəsti on dəqiqədən çox çəkməməlidir. Daha yavaş dəst lokal olaraq daha az işə salınır və onun cavabı developer artıq başqa işə keçəndən sonra gəlir.
- Determinizm. Kod dəyişmədən bəzən düşən test testin olmamasından da pisdir: insanlar pipeline-ı yaşıl olana qədər yenidən işə salır, növbəti real xəta da eyni münasibətlə qarşılanır. Fowler qeyri-deterministik testləri "faydasız" və "sürətlə yayılan infeksiya" adlandırır və onları avtomatik retry-ların arxasında gizlətmək yox, karantinə almaq və tez düzəltmək məsləhətini verir.
- Bir əmr. Developer-lər CI-ın işə saldığını eyni konfiqurasiya ilə lokal olaraq da işə sala bilməlidir.
Pull request-də testlərin review-u
Testləri koddan əvvəl oxu: onlar müəllifin dəyişiklikdən nə gözlədiyini deyir.
- Yeni davranış üçün onu göstərə bilən ən aşağı səviyyədə test varmı?
- Dəyişiklik olmasa, test düşərdimi? Bu, aydın deyilsə, branch-a keç (checkout), düzəlişi geri qaytar və testi işə sal.
- Assertion-lar nəticələri (qaytarılan dəyərlər, ekrandakı mətn, göndərilən sorğular), yoxsa daxili hissələri yoxlayır?
- Mövcud gözlənilən dəyərlər dəyişibmi? Yeni gözlənilən dəyərlər tələb edən refaktorinq refaktorinq deyil; hansı davranışın dəyişdiyini və bunun qəsdən olub-olmadığını soruş.
- Hər yenilənmiş snapshot dəyişikliklə izah olunurmu?
Testlər dizayn siqnalı kimi
Komponenti test etmək üçün ondan çox mock lazımdırsa, problem testdə yox, dizayndadır: komponent həddindən artıq çox iş görür və ya çox sayda modula birbaşa müraciət edir. Yazılması əziyyətli olan test çox vaxt kodun dəyişdirilməsinin də əziyyətli olacağına dair ilk xəbərdarlıqdır.
Tests protect a codebase only if they run on every change and nothing merges while they fail. A pipeline for a pull request runs the cheapest checks first, so a typo fails in seconds rather than after a long browser run:
npx tsc --noEmit
npx eslint .
npx vitest run --coverage
npx playwright testOn a developer machine, vitest starts in watch mode, but in CI (when process.env.CI is set) or in a non-interactive terminal it does a single run. Two CI defaults matter for review. Vitest doesn't write snapshots in CI: a missing, changed or obsolete snapshot fails the run instead of being recorded, so a snapshot changes only when someone updates it locally and commits the diff. And allowOnly is off in CI, so a forgotten test.only fails the suite instead of silently skipping every other test.
Keep the suite fast and trustworthy
- A time budget. Fowler cites Kent Beck's rule of thumb that the commit suite should take no more than ten minutes. A slower suite is run less often locally, and its feedback arrives after the developer has moved on.
- Determinism. A test that sometimes fails without a code change is worse than no test: people rerun the pipeline until it is green, and the next real failure gets the same treatment. Fowler calls non-deterministic tests "useless" and "a virulent infection", and advises quarantining them and fixing them quickly rather than hiding them behind automatic retries.
- One command. Developers should be able to run locally exactly what CI runs, with the same configuration.
Reviewing tests in a pull request
Read the tests before the code: they say what the author meant the change to do.
- Is there a test for the new behaviour, at the lowest level that can show it?
- Would it fail without the change? If that is not obvious, check out the branch, revert the fix and run the test.
- Do the assertions check results (return values, text on screen, requests sent) or internals?
- Did existing expected values change? A refactor that needs new expected values is not a refactor; ask which behaviour changed and whether that was intended.
- Is every updated snapshot explained by the change?
Tests as a design signal
If a component needs a dozen mocks before it can be tested, the problem is the design, not the test: it does too much or reaches into too many modules directly. A test that is painful to write is often the first warning that the code will be painful to change.
Bug hesabatı: əvvəlcə reqressiya testi, düzgün səviyyədə
Bug hesabatı test əlavə etmək üçün ən yaxşı andır: kodun orada kövrək olduğunu bilirsən və əlində konkret uğursuz hal var. Martin Fowler yüksək səviyyəli testin aşkarladığı bug üçün belə məsləhət verir: düzəltməzdən əvvəl onu unit testlə təkrarla. Ham Vocke-nin variantı: yüksək səviyyəli test xəta tapıbsa və heç bir aşağı səviyyəli test düşmürsə, aşağı səviyyəli test yaz.
Hesabat: "Səbətin cəmi düz 50 olanda pulsuz çatdırılma tətbiq olunmur."
- Bug-ı onu göstərə bilən ən aşağı səviyyədə təkrarla. Qayda təmiz funksiya olan
shippingCost-dadır, ona görə bunu unit test edə bilər:
test("ships free at exactly the threshold", () => {
expect(shippingCost(50, "AZ")).toBe(0);
});- Testin hesabatdakı səbəbə görə düşdüyünü gör:
0əvəzinə5alır. Test keçirsə, bug başqa yerdədir və test səni indicə səhv düzəlişdən xilas edib. - Kodu düzəlt (
total > 50total >= 50olur), testin keçdiyini gör, sonra bütün test dəstini işə sal: başqa kod köhnə qaydaya güvənmiş ola bilər. - Testi saxla. O, düz 50-nin pulsuz çatdırıldığı qərarını sənədləşdirir və kimsə bug-ı geri qaytarsa, düşür.
Səviyyəni seçmək
Bug-ı təkrarlayan ən aşağı səviyyə adətən doğru seçimdir, amma hər bug bir unit-in içində yaşamır:
| Bug harada | Nə yaz | Nümunə |
|---|---|---|
| bir funksiya və ya modulun içindəki qaydada | unit test | yuvarlaqlaşdırma, tarix sərhədi, reducer halı |
| hissələr arasındakı müqavilədə | inteqrasiya testi | form qty göndərir, API client quantity oxuyur |
| yalnız işləyən tətbiqin göstərdiyi şeydə | end-to-end test | deploy-dan sonra 404 verən route, heç vaxt göndərilməyən cookie |
Bug-ı istifadəçi və ya end-to-end test tapıbsa və onu aşağı səviyyəli test də təkrarlaya bilirsə, aşağı səviyyəli testə üstünlük ver: o, daha sürətlidir, səbəbi göstərir və flaky olmur. End-to-end testi aşağı səviyyələrin göstərə bilmədiyi bug-lar üçün saxla.
Test nə vaxt dəyməz
Məntiq yenidən sına bildiyi yerdə reqressiya testi ucuz sığortadır. Düzəliş kodda yox, datada olanda (bazadakı səhv qeyd), bug mətndəki hərf səhvi olanda və ya onu təkrarlayan yeganə test o qədər yavaş və ya etibarsız olanda ki, komanda onu tezliklə ötürməyə başlayacaq, onun faydası azdır. Belə halda bunu pull request-də yaz ki, review edən boşluğun qəsdən buraxıldığını bilsin.
A bug report is the best moment to add a test: you know the code is fragile there, and you have a concrete failing case. Martin Fowler's advice for a bug exposed by a high-level test is to replicate it with a unit test before fixing it, and Ham Vocke's version is: if a higher-level test spots an error and no lower-level test fails, write a lower-level test.
The report: "Free shipping is not applied when the cart total is exactly 50."
- Reproduce it at the lowest level that can show it. The rule lives in
shippingCost, a pure function, so a unit test can:
test("ships free at exactly the threshold", () => {
expect(shippingCost(50, "AZ")).toBe(0);
});- Watch it fail for the reported reason: it receives
5instead of0. If it passes, the bug is somewhere else, and the test has just saved you from a wrong fix. - Fix the code (
total > 50becomestotal >= 50), watch the test pass, then run the whole suite: some other code may have relied on the old rule. - Keep the test. It documents the decision that exactly 50 ships free, and it fails if anyone reintroduces the bug.
Choosing the level
The lowest level that reproduces the bug is usually right, but not every bug lives inside one unit:
| The bug is in | Write | Example |
|---|---|---|
| a rule inside one function or module | a unit test | rounding, a date boundary, a reducer case |
| the contract between parts | an integration test | the form sends qty, the API client reads quantity |
| something only the running app shows | an end-to-end test | a route that 404s after a deploy, a cookie that is never sent |
If a user or an end-to-end test found the bug and a lower-level test can reproduce it, prefer the lower-level test: it is faster, points at the cause and doesn't flake. Keep an end-to-end test for the bugs nothing lower can show.
When a test is not worth it
A regression test is cheap insurance when logic can break again. It adds little when the fix was in data rather than code (a bad record in the database), when the bug was a typo in a text, or when the only test that reproduces it would be so slow or unreliable that the team would soon skip it. Then say so in the pull request, so the reviewer knows the gap is deliberate.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Testlər mənə kodu dəyişməyə əminlik verir və onun nə etməli olduğunu təsvir edir. Səviyyəni nəyin sına biləcəyinə görə seçirəm: məntiq üçün unit testlər, hissələrin birlikdə işləməsi üçün inteqrasiya testləri (React tətbiqində bu, komponentləri real uşaqları ilə render edib yalnız şəbəkəni saxtalaşdırmaq deməkdir) və heç vaxt sınmamalı olan ssenarilər üçün real brauzerdə bir neçə end-to-end test. Yuxarı səviyyələr hər test üçün daha çox əminlik verir, amma daha yavaş, daha flaky və debug etmək üçün daha çətindir. Davranışı implementasiya detalları üzərindən yox, public API üzərindən test edirəm ki, refaktorinq testləri sındırmasın. Coverage mənə nəyin test olunmadığını göstərir, testlərin yaxşı olduğunu isə demir."
Gözlənilən suallar
- Piramida, yoxsa trophy? Hər ikisini və müəlliflərini adlandır (Mike Cohn, Martin Fowler-in izahı ilə; Kent C. Dodds), fikir ayrılığının çoxunun "unit"-in nə olduğu barədə olduğunu izah et və bu tip tətbiq üçün nəyi seçəcəyini və niyə seçəcəyini de.
- İmplementasiya detalı nədir? Çağıranların görə və istifadə edə bilmədiyi şey. False negative və false positive arqumentini nümunə ilə göstər, məsələn, komponentin state-ini oxuyan test.
- 100% coverage yaxşı məqsəddirmi? Yox: coverage nəyin yoxlandığını yox, nəyin işlədiyini göstərir. Ondan test olunmamış kodu tapmaq üçün və CI-da alt hədd kimi istifadə et.
- Bug hesabatı ilə necə işləyirsən? Bug-ı onu göstərən ən aşağı səviyyədə uğursuz testlə təkrarla, kodu düzəlt, testi saxla.
- Nəyi test etməzdin? Üçüncü tərəf kodunu, trivial kodu, tip yoxlayıcısının sübut etdiyini, stil detallarını.
- End-to-end testlər niyə flaky olur və bununla nə edirsən? Hərəkətli hissələr çoxdur: şəbəkə, data, vaxt, brauzer. Onları az saxla, deterministik et, flaky olanları retry etmək əvəzinə karantinə al və düzəlt.
Bal itirməyə səbəb olan səhvlər
- Səviyyələri alətə görə müəyyən etmək ("Vitest unit-dir, Playwright E2E"). Bütöv formu real API client-i və saxta şəbəkə ilə render edən Vitest testi inteqrasiya testidir.
- Piramidaya və ya trophy-yə xərclərin modeli kimi yox, qayda kimi baxmaq.
- Yalnız mock-un çağırıldığını yoxlayan testi, həmin çağırış müqavilənin hissəsi olmadığı halda, "davranışın testi" adlandırmaq.
- "Bizdə 90% coverage var" sözünü kodun yaxşı test olunduğuna sübut kimi təqdim etmək.
Senior səviyyəni göstərən məqamlar
Test dəstindən işlətmə xərcləri olan bir şey kimi danış: CI nə qədər çəkir, hansı testlər flaky-dir və onları kim düzəldir, hansı testlər hər refaktorinqdə sınır, hansı bug-lar production-a çatıb və onları hansı səviyyə tutmalı idi. Testləri riskə görə yerləşdir: ödənişlər və giriş end-to-end testlərlə əhatə olunur, tarix köməkçisi unit testlər cədvəli alır, statik marketinq səhifəsi isə demək olar ki, heç nə. Test etmək çətin olan modula daha çox mock üçün səbəb kimi yox, dizayn problemi kimi bax.
A 30-second answer. "Tests give me confidence to change code and describe what it must do. I choose the level by what can break: unit tests for logic, integration tests for how parts work together, which in a React app means rendering components with their real children and faking only the network, and a few end-to-end tests in a real browser for the journeys that must never break. Higher levels give more confidence per test but are slower, flakier and harder to debug. I test behaviour through the public API, not implementation details, so refactors don't break tests. Coverage shows me what is untested; it doesn't tell me the tests are good."
Questions you are likely to get
- Pyramid or trophy? Name both and their authors (Mike Cohn, described by Martin Fowler; Kent C. Dodds), explain that much of the disagreement is about what a "unit" is, and say what you would choose for this kind of app and why.
- What is an implementation detail? Something callers can't see or use. Give the false-negative and false-positive argument with an example, such as a test that reads a component's state.
- Is 100% coverage a good goal? No: coverage shows what ran, not what was checked. Use it to find untested code and as a floor in CI.
- How do you handle a bug report? Reproduce it with a failing test at the lowest level that shows it, fix the code, keep the test.
- What would you not test? Third-party code, trivial code, what the type checker proves, styling details.
- Why are end-to-end tests flaky, and what do you do about it? Many moving parts: network, data, timing, the browser. Keep them few, make them deterministic, quarantine and fix flaky ones instead of retrying.
Mistakes that cost points
- Defining levels by tool ("Vitest is unit, Playwright is E2E"). A Vitest test that renders a whole form with its real API client and a fake network is an integration test.
- Treating the pyramid or the trophy as a rule rather than a model of costs.
- Calling a test that only checks that a mock was called "testing behaviour" when that call is not part of the contract.
- Offering "we have 90% coverage" as proof that the code is well tested.
Senior signal
Talk about the suite as something with running costs: how long CI takes, which tests flake and who fixes them, which tests break on every refactor, which bugs reached production and which level should have caught them. Place tests by risk: payments and sign-in get end-to-end coverage, a date helper gets a table of unit tests, a static marketing page gets almost none. Treat a hard-to-test module as a design problem, not as a reason to mock more.
Testləri review edərkən nəyi yoxlamalı
Yazmadığın testləri — komanda yoldaşının pull request-ində, kitabxananın nümunəsində və ya AI assistentin təklifində — review edəndə bu siyahıdan istifadə et. Yaşıl CI run-ında zəif test də güclü test kimi görünür; bu review-u ötürsən, "test olunmuş" bug-lar və onlarla testi sındıran refaktorinqlər alırsan.
- Davranış sınsa, test düşərdimi? Kodu qəsdən sındır və ya düzəlişi geri qaytar və testi işə sal. Yaşıl qalan, heç bir
expect-i olmayan və ya gözlənilən dəyəri kodla eyni məntiqlə hesablayan test heç nəyi yoxlamır; Vitest-dəexpect.requireAssertionsseçimi assertion-sız testləri uğursuz edir. - Test çağıranın görə bildiyi şeyi yoxlayırmı? Qaytarılan dəyərlər, atılan xətalar, ekrandakı mətn və göndərilən sorğular refaktorinqdən sağ çıxır. Private sahələrə, daxili state-ə və ya daxili köməkçi funksiyaların çağırışlarına dair assertion-lar hər yenidən yazılmada sınır və yenə də real bug-ları buraxır.
- Test davranışı göstərə bilən ən aşağı səviyyədədirmi? Qaydaların yeri sürətli unit testlər, bağlantıların yeri inteqrasiya testləridir. Bir validasiya qaydası üçün end-to-end test yavaş və flaky olur, bütün qonşuları mock olunmuş unit test isə iki modulun razılaşmadığı sahə adını tuta bilmir.
- Hər ad bir davranışı ifadə edirmi?
describevətestadlarını cümlə kimi oxu: "applyCoupon > rejects an expired coupon" nəyin sındığını deyir; "works" və ya "and" ilə birləşdirilmiş ad bir neçə halı gizlədir. - Yalnız uğurlu ssenari yox, kənar hallar və xəta yolları da test olunubmu? Boş girişə, sıfıra, "düz 50" kimi sərhədlərə və reject olunmuş sorğulara bax. Coverage hesabatı heç bir testin girmədiyi budaqları göstərir.
- Test özündən kənar nədənsə asılıdırmı? Başqa testlərin qoyub getdiyi state, real saat, təsadüfi dəyərlər və ya şəbəkə testin keçib-keçməməsini təsadüfdən asılı edir. Yoxlamaq üçün faylı tək və təsadüfi sıra ilə işə sal (
vitest run cart.test.ts --sequence.shuffle). - Dəyişmiş hər gözlənilən dəyər və snapshot qəsdəndirmi? Hansı davranışın niyə dəyişdiyini soruş. Heç kimin oxumadığı yenilənmiş snapshot qəbul edilmiş bug-dır.
Use this list when you review tests you did not write: in a teammate's pull request, in a library's example or in an AI assistant's suggestion. In a green CI run a weak test looks the same as a strong one; skip this review, and you get bugs that are "covered" and refactors that break dozens of tests.
- Would the test fail if the behaviour broke? Break the code on purpose, or revert the fix, and run it. A test that stays green, has no
expect, or computes the expected value with the same logic as the code checks nothing; Vitest'sexpect.requireAssertionsoption makes tests without assertions fail. - Does it check what a caller can observe? Return values, thrown errors, text on the screen and requests sent survive refactors. Assertions on private fields, internal state or calls to internal helpers break on every rewrite and still miss real bugs.
- Is it at the lowest level that can show the behaviour? Rules belong in fast unit tests, wiring in integration tests. An end-to-end test for one validation rule is slow and flaky, and a unit test with every neighbour mocked can't catch a field name that two modules disagree on.
- Does each name state one behaviour? Read
describeandtestnames as a sentence: "applyCoupon > rejects an expired coupon" says what broke; "works", or a name joined with "and", hides several cases. - Are edge cases and error paths tested, not only the happy path? Look for empty input, zero, boundaries such as "exactly 50" and rejected requests. The coverage report shows branches that no test ran.
- Does the test depend on anything outside itself? State left by other tests, the real clock, random values or the network make it pass or fail by chance. Run the file alone and in random order (
vitest run cart.test.ts --sequence.shuffle) to check. - Is every changed expected value or snapshot intended? Ask which behaviour changed and why. An updated snapshot that nobody read is an accepted bug.