Unit testlər və test double-lar
Vitest ilə unit testlər yazmaq: test və describe, bərabərlik matcher-ləri, xətalar və promise-lər, təmiz funksiyalar və ötürülən asılılıqlarla kodu test oluna bilən etmək, test double-ların beş növü, vi.fn, vi.spyOn və onların bərpası, testlərin təcrid olunması, həddindən artıq mock və snapshot testlərin hüdudları.
Oxu səviyyəsi
Seçilmiş səviyyəyə qədər olan bölmələr göstərilir.
Başlamazdan əvvəl
Bu mövzu Junior səviyyəsindən başlayır.
Vitest ilə ilk unit test
kodun bir hissəsini seçdiyin girişlərlə çağırır və çıxışı yoxlayır. Test etmək üçün ən asan kod təmiz funksiyadır (pure function): onun nəticəsi yalnız arqumentlərindən asılıdır və o, özündən kənarda heç nəyi dəyişmir. Nəyisə hazırlamaq, təmizləmək və ya gözləmək lazım deyil: çağırırsan və müqayisə edirsən.
// price.ts
export function formatPrice(cents: number, currency = "AZN"): string {
if (!Number.isInteger(cents)) throw new TypeError("cents must be an integer");
return `${(cents / 100).toFixed(2)} ${currency}`;
}// price.test.ts
import { describe, expect, it, test } from "vitest";
import { formatPrice } from "./price";
describe("formatPrice", () => {
it("formats cents with two decimals", () => {
expect(formatPrice(1999)).toBe("19.99 AZN");
});
it("uses the currency it is given", () => {
expect(formatPrice(250, "EUR")).toBe("2.50 EUR");
});
test.each([
[0, "0.00 AZN"],
[5, "0.05 AZN"],
[100000, "1000.00 AZN"],
])("formats %i as %s", (cents, expected) => {
expect(formatPrice(cents)).toBe(expected);
});
});test(name, fn)testi təyin edir.iteyni funksiyanın başqa adıdır: onunlait("formats…")ingiliscə cümlə kimi oxunur.describe(name, fn)testləri qruplaşdırır; uğursuzluqformatPrice > formats cents with two decimalskimi göstərilir.expect(value)assertion-ı başladır,toBekimi matcher isə onu tamamlayır. Uğursuz matcher xəta atır və test uğursuz olur..notistənilən matcher-i tərsinə çevirir:expect(x).not.toBe(0).test.eacheyni testi cədvəlin hər sətri üçün bir dəfə işə salır; addakı%ivə%ssətrin dəyərləri ilə əvəz olunur.
Vitest bu funksiyaları default olaraq qlobal etmir (globals: false), ona görə onları "vitest"-dən import edirsən. Testlər default olaraq Node.js mühitində işləyir və bu, təmiz məntiq üçün uyğundur; komponent testləri environment seçimini jsdom və ya happy-dom edir. İşləyərkən faylları izləmək üçün npx vitest, bir dəfəlik run üçün npx vitest run əmrini işə sal.
Halları seçmək
Hər test funksiyanın müqaviləsinin bir nümunəsidir: adi giriş, sərhədlər (sıfır, real ola biləcək ən böyük dəyər) və yanlış giriş. Hər testi göstərdiyi qaydaya görə adlandır. Gözlənilən dəyərləri literal kimi yaz ("19.99 AZN"), kodun istifadə etdiyi düsturla yenidən hesablama: hesablamanı təkrarlayan test onun bug-larını da təkrarlayır.
Funksiya saatı oxuduğu, şəbəkəyə müraciət etdiyi və ya render olunmuş komponent tələb etdiyi üçün onu bu yolla test etmək çətindirsə, bu, adətən onu bölməyin vaxtı olduğuna işarədir: qaydaları saxlayan təmiz nüvə və yan təsirləri (side effect) icra edən nazik qat.
A calls one piece of code with chosen inputs and checks the output. The easiest code to test is a pure function: its result depends only on its arguments, and it changes nothing outside itself. There is nothing to set up, clean up or wait for: you call it and compare.
// price.ts
export function formatPrice(cents: number, currency = "AZN"): string {
if (!Number.isInteger(cents)) throw new TypeError("cents must be an integer");
return `${(cents / 100).toFixed(2)} ${currency}`;
}// price.test.ts
import { describe, expect, it, test } from "vitest";
import { formatPrice } from "./price";
describe("formatPrice", () => {
it("formats cents with two decimals", () => {
expect(formatPrice(1999)).toBe("19.99 AZN");
});
it("uses the currency it is given", () => {
expect(formatPrice(250, "EUR")).toBe("2.50 EUR");
});
test.each([
[0, "0.00 AZN"],
[5, "0.05 AZN"],
[100000, "1000.00 AZN"],
])("formats %i as %s", (cents, expected) => {
expect(formatPrice(cents)).toBe(expected);
});
});test(name, fn)defines a test.itis the same function under another name, so thatit("formats…")reads as a sentence.describe(name, fn)groups tests; a failure is reported asformatPrice > formats cents with two decimals.expect(value)starts an assertion and a matcher such astoBefinishes it. A failing matcher throws, and the test fails..notnegates any matcher:expect(x).not.toBe(0).test.eachruns the same test once for each row of a table;%iand%sin the name are replaced by the row's values.
Vitest doesn't make these functions global by default (globals: false), so you import them from "vitest". Tests run in a Node.js environment by default, which suits pure logic; component tests switch the environment option to jsdom or happy-dom. Run npx vitest to watch files while you work and npx vitest run for a single run.
Choosing the cases
Each test is one example of the function's contract: a typical input, the boundaries (zero, the largest realistic value) and invalid input. Name each test after the rule it shows. Write expected values as literals ("19.99 AZN"), never recomputed with the same formula the code uses: a test that repeats the calculation repeats its bugs.
If a function is hard to test this way because it reads the clock, calls the network or needs a rendered component, that is usually a hint to split it: a pure core that holds the rules, and a thin layer that does the side effects.
toBe, toEqual və toStrictEqual
toBe dəyərləri Object.is ilə müqayisə edir: bu, === ilə eynidir, yalnız NaN NaN-a bərabər sayılır, 0 isə -0-dan fərqlənir. Sətirlər, ədədlər və boolean-lar üçün elə istədiyin budur. Obyektlər və massivlər üçün isə o, eyniliyi (identity) yoxlayır, ona görə məzmunu eyni olan iki obyekt toBe ilə bərabər deyil:
const a = { id: 1, tags: ["new"] };
const b = { id: 1, tags: ["new"] };
expect(a).toBe(a);
expect(a).not.toBe(b);
expect(a).toEqual(b);toEqual rekursiv müqayisə edir: eyni açarlar və ən dərinə qədər bərabər dəyərlər. Vitest sənədləri onun toStrictEqual-dan daha yumşaq olduğu üç yeri sadalayır:
- dəyəri
undefinedolan açarlar nəzərə alınmır:{ a: undefined, b: 2 }və{ b: 2 }bərabər sayılır; - massivdəki boşluqlar yoxlanmır:
[, 1]və[undefined, 1]bərabər sayılır; - obyektin tipi yoxlanmır: class-ın instance-ı eyni sahələri olan adi obyektə bərabər sayılır.
class Money {
amount: number;
currency: string;
constructor(amount: number, currency: string) {
this.amount = amount;
this.currency = currency;
}
}
const price = new Money(5, "AZN");
expect(price).toEqual({ amount: 5, currency: "AZN" });
expect(price).not.toStrictEqual({ amount: 5, currency: "AZN" });
expect({ amount: 5, note: undefined }).toEqual({ amount: 5 });
expect({ amount: 5, note: undefined }).not.toStrictEqual({ amount: 5 });Dəqiq forma müqavilənin hissəsidirsə, toStrictEqual yaz: reducer-in növbəti state-i, API-yə göndərilən payload, class-ın instance-ı olmalı olan dəyər. "Eyni data" kifayət edəndə toEqual yaz.
Gündəlik digər matcher-lər
toMatchObject(subset): obyektdə ən azı bu xüsusiyyətlər var, rekursiv yoxlanılır; əlavə xüsusiyyətlərə icazə verilir. Bütün sahələri sadalamadan "yeni sifarişin statusupending-dir" demək üçün yaxşıdır.toContain(item): massivdə element və ya sətirdə alt sətir.toHaveLength(n).length-i yoxlayır.toBeCloseTo(n, digits?): kəsr ədədli (floating-point) nəticələr üçün.0.1 + 0.2əslində0.30000000000000004-dür, ona görətoBe(0.3)uğursuz olur,toBeCloseTo(0.3)isə keçir; başqa ədəd ötürməsən, nöqtədən sonra 2 rəqəm yoxlanılır.toBeNull(),toBeUndefined(),toBeTruthy(),toBeFalsy(). Ən konkret matcher-i seç: dəyər booleantrueolmalıdırsa,toBe(true)yaz, çünkitoBeTruthy()1-i və"no"-nu da qəbul edir.
toBe compares with Object.is: the same as ===, except that NaN equals NaN and 0 differs from -0. For strings, numbers and booleans that is what you want. For objects and arrays it checks identity, so two objects with the same contents are not toBe-equal:
const a = { id: 1, tags: ["new"] };
const b = { id: 1, tags: ["new"] };
expect(a).toBe(a);
expect(a).not.toBe(b);
expect(a).toEqual(b);toEqual compares recursively: the same keys with equal values, all the way down. The Vitest docs list three ways in which it is more lenient than toStrictEqual:
- keys whose value is
undefinedare ignored:{ a: undefined, b: 2 }equals{ b: 2 }; - array holes are not checked:
[, 1]equals[undefined, 1]; - the object's type is not checked: a class instance equals a plain object with the same fields.
class Money {
amount: number;
currency: string;
constructor(amount: number, currency: string) {
this.amount = amount;
this.currency = currency;
}
}
const price = new Money(5, "AZN");
expect(price).toEqual({ amount: 5, currency: "AZN" });
expect(price).not.toStrictEqual({ amount: 5, currency: "AZN" });
expect({ amount: 5, note: undefined }).toEqual({ amount: 5 });
expect({ amount: 5, note: undefined }).not.toStrictEqual({ amount: 5 });Use toStrictEqual when the exact shape is part of the contract: a reducer's next state, a payload sent to an API, a value that must be an instance of a class. Use toEqual when "the same data" is enough.
Other everyday matchers
toMatchObject(subset): the object has at least these properties, checked recursively; extra properties are allowed. Good for "the new order has statuspending" without listing every field.toContain(item): an item in an array, or a substring in a string.toHaveLength(n)checks.length.toBeCloseTo(n, digits?): for floating-point results.0.1 + 0.2is0.30000000000000004, sotoBe(0.3)fails, whiletoBeCloseTo(0.3)passes; it checks 2 digits after the point unless you pass another number.toBeNull(),toBeUndefined(),toBeTruthy(),toBeFalsy(). Prefer the most specific matcher: if the value must be the booleantrue, writetoBe(true), becausetoBeTruthy()also accepts1and"no".
Xətaları və promise-ləri test etmək
Xətalar
toThrow funksiyanı çağırır və onun xəta atdığını yoxlayır. Ona funksiyanın özünü ötür, çağırışın nəticəsini yox:
expect(() => formatPrice(1.5)).toThrow("cents must be an integer");
expect(() => formatPrice(1.5)).toThrow(/integer/);
// ✗ formatPrice arqument hesablanarkən, expect işə düşməmiş xəta atır
expect(formatPrice(1.5)).toThrow();Son sətirdə JavaScript expect-in arqumentini hesablamaq üçün formatPrice(1.5)-i çağırır, ona görə xəta toThrow onu tuta bilməmiş çölə çıxır və test həmin xəta ilə uğursuz olur. Vitest sənədləri bunu açıq deyir: kodu funksiyaya bükməlisən, əks halda xəta tutulmayacaq. Sətir arqumenti mesajın bir hissəsini (substring), regular expression isə şablonu yoxlayır. Yalnız "nəsə" atıldığını yox, mesajı da yoxla: TypeError: x is not a function atan hərf səhvi də arqumentsiz toThrow() yoxlamasından keçir.
Promise-lər
Test funksiyası async ola bilər; Vitest onun qaytardığı promise-i gözləyir. Ya dəyəri await et və adi matcher-lərdən istifadə et, ya da .resolves və .rejects yaz:
const api = {
getUser: async (id: number) => (id === 1 ? { id, name: "Leyla" } : null),
};
test("loads a user", async () => {
const user = await loadUser(1, api);
expect(user.name).toBe("Leyla");
});
test("rejects an unknown id", async () => {
await expect(loadUser(999, api)).rejects.toThrow("User 999 not found");
});.resolves və .rejects matcher-i promise-ə çevirir, ona görə sətir await olunmalıdır. Vitest 5.0-dan bəri belə assertion await olunmasa, test uğursuz olur; ondan əvvəl Vitest onu testin sonunda gözləyirdi və yalnız xəbərdarlıq çap edirdi. Ümumi qayda istənilən test runner-dən köhnədir: heç kimin await etmədiyi və ya qaytarmadığı promise testin hissəsi deyil, onun uğursuzluğu da testin uğursuzluğu sayılmır.
Nəticəni callback vasitəsilə bildirən kod üçün testin əvvəlində expect.assertions(n) düz n assertion-ın işlədiyini, expect.hasAssertions() isə ən azı birinin işlədiyini yoxlayır. Hər ikisi yeganə expect-i heç vaxt çağırılmayan callback-də qalan testi tutur.
Kiçik api obyekti real client-in yerinə əllə yazılmış əvəzedicidir: test double-ın ən sadə növü və loadUser-in client-i import etmək əvəzinə parametr kimi qəbul etməsinin səbəbi.
Errors
toThrow calls a function and checks that it throws. Pass it the function, not the result of calling it:
expect(() => formatPrice(1.5)).toThrow("cents must be an integer");
expect(() => formatPrice(1.5)).toThrow(/integer/);
// ✗ formatPrice throws while the argument is evaluated, before expect runs
expect(formatPrice(1.5)).toThrow();In the last line JavaScript calls formatPrice(1.5) to compute the argument for expect, so the error escapes before toThrow can catch it, and the test fails with that error. The Vitest docs put it plainly: you must wrap the code in a function, otherwise the error will not be caught. A string argument matches a substring of the message and a regular expression a pattern. Check the message, not only that "something" was thrown: a typo that throws TypeError: x is not a function also satisfies a bare toThrow().
Promises
A test function can be async; Vitest waits for the promise it returns. Either await the value and use ordinary matchers, or use .resolves and .rejects:
const api = {
getUser: async (id: number) => (id === 1 ? { id, name: "Leyla" } : null),
};
test("loads a user", async () => {
const user = await loadUser(1, api);
expect(user.name).toBe("Leyla");
});
test("rejects an unknown id", async () => {
await expect(loadUser(999, api)).rejects.toThrow("User 999 not found");
});.resolves and .rejects turn the matcher into a promise, so the line must be awaited. Since Vitest 5.0 such an assertion fails the test if it is not awaited; before that, Vitest awaited it at the end of the test and only printed a warning. The general rule is older than any test runner: a promise that nobody awaits or returns is not part of the test, so its failure is not the test's failure.
For code that reports results through a callback, expect.assertions(n) at the top of the test checks that exactly n assertions ran, and expect.hasAssertions() that at least one did. Both catch the test whose only expect sits in a callback that never fired.
The small api object is a hand-written stand-in for the real client: the simplest kind of test double, and the reason loadUser takes the client as a parameter instead of importing it.
Kodu test oluna bilən etmək: təmiz funksiyalar və ötürülən asılılıqlar
Komponentin içində yazılmış məntiqi yalnız komponenti render edərək test etmək olar. Eyni məntiq təmiz funksiya kimi hər hal üçün bir sətirlə test olunur. Tipik refaktorinq:
// əvvəl: qaydalar komponentin içindədir
function CheckoutSummary({ items, coupon }: Props) {
let subtotal = 0;
for (const item of items) subtotal += item.price * item.quantity;
const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
const shipping = subtotal - discount >= 100 ? 0 : 5;
return <Summary subtotal={subtotal} discount={discount} shipping={shipping} />;
}// sonra: qaydaları təmiz funksiya saxlayır
export function summarize(items: Item[], coupon?: string) {
const subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
const shipping = subtotal - discount >= 100 ? 0 : 5;
return { subtotal, discount, shipping, total: subtotal - discount + shipping };
}İndi komponent summarize(items, coupon)-u çağırır və nəticəni render edir. Hər qayda və qaydaların bir-birinə təsiri (endirim pulsuz çatdırılma həddinə sayılırmı?) sürətli unit test alır, bir-iki komponent testi isə rəqəmlərin ekrana çatdığını yoxlayır.
Yan təsirlər kənarda, asılılıqlar parametr kimi
Hər şey təmiz ola bilməz: kod saatı oxuyur, şəbəkəyə müraciət edir, storage-ə yazır. Bu çağırışları kənarda saxla və onlara içəridən əl uzatmaq əvəzinə parametr kimi ötür:
type Deps = {
now: () => Date;
post: (order: Order) => Promise<void>;
};
export async function placeOrder(cart: Cart, { now, post }: Deps) {
if (cart.items.length === 0) throw new Error("Cart is empty");
await post({ items: cart.items, placedAt: now().toISOString() });
}Tətbiq placeOrder(cart, { now: () => new Date(), post: api.postOrder }) çağırır. Test isə sabit saat və aldığını yadda saxlayan funksiya ötürür:
test("stamps the order with the current time", async () => {
const post = vi.fn(async (_order: Order) => {});
const now = () => new Date("2026-11-16T10:00:00Z");
await placeOrder({ items: [tea] }, { now, post });
expect(post).toHaveBeenCalledWith({
items: [tea],
placedAt: "2026-11-16T10:00:00.000Z",
});
});Bu, dependency injection-dır (asılılıqların ötürülməsi): asılılıqları çağıran tərəf verir. Xüsusi alət tələb etmir və asılılıqları funksiyanın imzasında göstərir. React-də eyni ideya props (onSubmit) və ya context kimi görünür.
Nəticədə hərtərəfli test etmək ucuz olan böyük təmiz nüvə və cəmi bir neçə test tələb edən nazik komponent və adapter qatı alınır.
Logic written inside a component can only be tested by rendering the component. The same logic as a pure function can be tested with one line per case. A typical refactor:
// before: the rules live in the component
function CheckoutSummary({ items, coupon }: Props) {
let subtotal = 0;
for (const item of items) subtotal += item.price * item.quantity;
const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
const shipping = subtotal - discount >= 100 ? 0 : 5;
return <Summary subtotal={subtotal} discount={discount} shipping={shipping} />;
}// after: a pure function holds the rules
export function summarize(items: Item[], coupon?: string) {
const subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
const discount = coupon === "SAVE10" && subtotal >= 50 ? subtotal * 0.1 : 0;
const shipping = subtotal - discount >= 100 ? 0 : 5;
return { subtotal, discount, shipping, total: subtotal - discount + shipping };
}The component now calls summarize(items, coupon) and renders the result. Each rule, and the way the rules interact (does the discount count towards free shipping?), gets a fast unit test, and one or two component tests check that the numbers reach the screen.
Side effects at the edge, dependencies passed in
Not everything can be pure: code reads the clock, calls the network, writes to storage. Keep those calls at the edge, and pass them in instead of reaching for them from inside:
type Deps = {
now: () => Date;
post: (order: Order) => Promise<void>;
};
export async function placeOrder(cart: Cart, { now, post }: Deps) {
if (cart.items.length === 0) throw new Error("Cart is empty");
await post({ items: cart.items, placedAt: now().toISOString() });
}The app calls placeOrder(cart, { now: () => new Date(), post: api.postOrder }). A test passes a fixed clock and a function that records what it receives:
test("stamps the order with the current time", async () => {
const post = vi.fn(async (_order: Order) => {});
const now = () => new Date("2026-11-16T10:00:00Z");
await placeOrder({ items: [tea] }, { now, post });
expect(post).toHaveBeenCalledWith({
items: [tea],
placedAt: "2026-11-16T10:00:00.000Z",
});
});This is dependency injection: the caller provides the collaborators. It needs no special tooling and shows the dependencies in the function's signature. In React the same idea appears as props (onSubmit) or context.
The result is a large pure core that is cheap to test thoroughly, and a thin shell of components and adapters that needs only a few tests.
Test double-lar: dummy, stub, spy, mock və fake
test zamanı real asılılığın yerini tutan istənilən obyekt və ya funksiyadır, kino kaskadyorunun (stunt double) aktyorun yerini tutduğu kimi. Termini və double-ların beş növünü Gerard Meszaros xUnit Test Patterns (2007) kitabında təqdim edib; adətən Martin Fowler-in TestDouble və Mocks Aren't Stubs məqalələrindəki qısa təriflərə istinad olunur:
- Dummy: ötürülür, amma heç vaxt istifadə olunmur; sadəcə parametr siyahısını doldurur. Məsələn, heç vaxt log yazmayan kod yolunda
loggerarqumenti. - Stub: test zamanı edilən çağırışlara əvvəlcədən hazırlanmış cavablar verir.
getRates: () => ({ USD: 1.7 })valyuta çevirməsini proqnozlaşdırıla bilən edir. - Spy: necə çağırıldığını da yadda saxlayan stub; test sonradan hansı mesajın "göndərildiyini" və neçə dəfə göndərildiyini yoxlaya bilər.
- Mock: alacağı çağırışlarla bağlı gözləntilərlə əvvəlcədən proqramlaşdırılır. Gözləmədiyi çağırışda uğursuz ola bilər, sonda isə gözlənilən bütün çağırışların baş verdiyi yoxlanılır.
- Fake: işləyən implementasiyadır, amma onu production üçün yararsız edən qısa yolu var, məsələn, verilənlər bazası əvəzinə datanı yaddaşda (in-memory) saxlayan repository.
// fake: real davranış, yaddaşda saxlanır
class InMemoryOrders implements OrderRepository {
#orders = new Map<string, Order>();
async save(order: Order) {
this.#orders.set(order.id, order);
}
async findById(id: string) {
return this.#orders.get(id) ?? null;
}
}Gündəlik danışıqda "mock"
vi.fn() hər çağırışı yadda saxlayan və proqramlaşdırdığın dəyəri qaytaran funksiya yaradır, yəni Meszaros-un terminləri ilə stub rolunu da oynaya bilən spy-dır. Vitest, Jest kimi, onu mock funksiya adlandırır və developer-lərin çoxu istənilən double-a deyir. Söhbətdə bu, problem deyil. Fərq nəyi yoxlayacağına qərar verəndə vacibdir:
- Stub və ya fake ilə test olunan kodun nəticəsini yoxlayırsan: qaytarılan cəmi, sonda fake repository-də nəyin saxlandığını. Fowler bunu state verification (vəziyyətin yoxlanması) adlandırır.
- Spy və ya mock ilə çağırışların özünü yoxlayırsan. Fowler bunu behaviour verification (davranışın yoxlanması) adlandırır, "double-ların bu növlərindən yalnız mock-lar davranışın yoxlanmasında israr edir" deyə qeyd edir və bu yolla yazılan testlərin "implementasiyaya daha sıx bağlı" olduğunu yazır.
Hansını seçməli
Real asılılıq sürətli və deterministikdirsə, məsələn, öz təmiz köməkçi funksiyalarındırsa, elə ondan istifadə et. Real olan yavaş və ya xaricidirsə, amma bir neçə çağırış boyu real davranış lazımdırsa (saxla, sonra tap), fake götür. Konkret cavab qaytartmaq üçün stub-dan istifadə et: xəta, boş siyahı, məzənnə. Çağırışları spy ilə yalnız çağırışın özü çağıran üçün vacib nəticə olanda yoxla, məsələn, email göndəriləndə və ya onSubmit form dəyərlərini alanda; qalan hallarda nəticəni yoxla.
A is any object or function that stands in for a real collaborator during a test, the way a stunt double stands in for an actor. Gerard Meszaros introduced the term and five kinds of doubles in xUnit Test Patterns (2007); Martin Fowler's short definitions in TestDouble and Mocks Aren't Stubs are the ones usually quoted:
- Dummy: passed around but never used; it only fills a parameter list. A
loggerargument on a code path that never logs. - Stub: gives canned answers to the calls made during the test.
getRates: () => ({ USD: 1.7 })makes a currency conversion predictable. - Spy: a stub that also records how it was called, so the test can check afterwards which message was "sent" and how many times.
- Mock: pre-programmed with expectations of the calls it should receive. It can fail on a call it doesn't expect, and at the end it is verified that every expected call happened.
- Fake: a working implementation with a shortcut that makes it unfit for production, such as an in-memory repository instead of a database.
// a fake: real behaviour, kept in memory
class InMemoryOrders implements OrderRepository {
#orders = new Map<string, Order>();
async save(order: Order) {
this.#orders.set(order.id, order);
}
async findById(id: string) {
return this.#orders.get(id) ?? null;
}
}"Mock" in everyday speech
vi.fn() creates a function that records every call and returns whatever you program, so in Meszaros' terms it is a spy that can also act as a stub. Vitest, like Jest, calls it a mock function, and most developers say for any double. That is fine in conversation. The distinction matters when you decide what to assert:
- With a stub or a fake, you check the result of the code under test: the returned total, what the fake repository holds afterwards. Fowler calls this state verification.
- With a spy or a mock, you check the calls themselves. Fowler calls this behaviour verification, notes that "only mocks insist upon behavior verification", and that tests written this way are "more coupled to the implementation".
Picking one
Use the real collaborator when it is fast and deterministic, such as your own pure helpers. Use a fake when the real one is slow or external but you need realistic behaviour across calls (save, then find). Use a stub to force a specific answer: an error, an empty list, a rate. Check calls with a spy only when the call itself is the outcome the caller cares about, such as an email being sent or onSubmit receiving the form values; otherwise assert on the result.
vi.fn, vi.spyOn və onların bərpası
vi.fn(impl?) yeni mock funksiya yaradır. İmplementasiya verilməsə, undefined qaytarır; verilsə, onu işə salır və çağırışı yadda saxlayır:
import { expect, test, vi } from "vitest";
test("reports each failed upload", () => {
const report = vi.fn();
reportFailures([{ name: "a.png", ok: false }, { name: "b.png", ok: true }], report);
expect(report).toHaveBeenCalledTimes(1);
expect(report).toHaveBeenCalledWith("a.png failed");
});Onu mockReturnValue(v), mockReturnValueOnce(v) (yalnız növbəti çağırış üçün), mockResolvedValue(v), mockRejectedValue(e) və ya mockImplementation(fn) ilə proqramlaşdır. toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith və toHaveBeenLastCalledWith ilə yoxla, ya da report.mock.calls-u (hər çağırış üçün arqumentlər massivi) və report.mock.results-u oxu. Tipli kodda vi.fn<typeof sendEmail>() yazsan, TypeScript proqramlaşdırdığın dəyərləri real imza ilə yoxlayır. Bir tələ: Vitest arqumentləri reference ilə saxlayır, yəni kod obyekti ötürdükdən sonra onu dəyişsə, toHaveBeenCalledWith dəyişmiş obyektlə müqayisə edir.
vi.spyOn(object, "method") mövcud obyektin metodunu default olaraq orijinalı çağırmağa davam edən mock ilə əvəz edir. Ondan real metodu izləmək üçün istifadə et, ya da davranışını əvəz etmək üçün .mockImplementation() və ya .mockReturnValue() zəncirlə:
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
parseConfig({ retries: "3" });
expect(warn).toHaveBeenCalledWith("retries should be a number");
warn.mockRestore();Clear, reset, restore
console kimi paylaşılan obyektə qoyulmuş spy, nəsə orijinalı geri qaytarmasa, testdən sonra da yerində qalır. Hər metod əvvəlkindən daha çox iş görür:
| çağırış tarixçəsini silir | implementasiyanı sıfırlayır | orijinal metodu geri qaytarır | |
|---|---|---|---|
mockClear() | bəli | xeyr | xeyr |
mockReset() | bəli | bəli | xeyr |
mockRestore() | bəli | bəli | bəli, vi.spyOn üçün |
"Sıfırlamaq" mock-un yaradıldığı vəziyyətə qayıtmaq deməkdir: vi.fn(impl) yenidən impl-ə, vi.fn() undefined qaytarmağa, vi.spyOn spy-ı isə real metodu çağırmağa qayıdır. vi.fn() mock-unda mockRestore() mockReset() ilə eyni işi görür.
vi.clearAllMocks() və vi.resetAllMocks() ilk ikisini bütün mock-lara tətbiq edir. vi.restoreAllMocks() isə yalnız vi.spyOn ilə əvəz olunmuş metodları geri qaytarır; tarixçəni silmir və implementasiyaları sıfırlamır. clearMocks, mockReset və restoreMocks config seçimləri onları hər testdən əvvəl avtomatik çağırır. Vitest 5-dən bəri clearMocks default olaraq aktivdir, mockReset və restoreMocks isə söndürülü qalır, ona görə testlər paylaşılan obyektlərə spy qoyursa, restoreMocks: true-nu aktiv et (və ya afterEach-də restore et).
vi.fn(impl?) creates a new mock function. Without an implementation it returns undefined; with one, it runs it and records the call:
import { expect, test, vi } from "vitest";
test("reports each failed upload", () => {
const report = vi.fn();
reportFailures([{ name: "a.png", ok: false }, { name: "b.png", ok: true }], report);
expect(report).toHaveBeenCalledTimes(1);
expect(report).toHaveBeenCalledWith("a.png failed");
});Program it with mockReturnValue(v), mockReturnValueOnce(v) (next call only), mockResolvedValue(v), mockRejectedValue(e) or mockImplementation(fn). Check it with toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith and toHaveBeenLastCalledWith, or read report.mock.calls (one array of arguments per call) and report.mock.results. For typed code, vi.fn<typeof sendEmail>() makes TypeScript check the programmed values against the real signature. One trap: Vitest stores arguments by reference, so if the code mutates an object after passing it, toHaveBeenCalledWith compares against the mutated object.
vi.spyOn(object, "method") replaces a method on an existing object with a mock that still calls the original by default. Use it to watch a real method, or chain .mockImplementation() or .mockReturnValue() to replace its behaviour:
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
parseConfig({ retries: "3" });
expect(warn).toHaveBeenCalledWith("retries should be a number");
warn.mockRestore();Clear, reset, restore
A spy on a shared object such as console stays in place after the test unless something puts the original back. Each method does more than the previous one:
| clears call history | resets the implementation | puts the original method back | |
|---|---|---|---|
mockClear() | yes | no | no |
mockReset() | yes | yes | no |
mockRestore() | yes | yes | yes, for vi.spyOn |
"Resets" means back to what the mock was created with: vi.fn(impl) returns to impl, vi.fn() to returning undefined, and a vi.spyOn spy to calling the real method. On a vi.fn() mock, mockRestore() does the same as mockReset().
vi.clearAllMocks() and vi.resetAllMocks() apply the first two to every mock. vi.restoreAllMocks() only puts back methods replaced by vi.spyOn; it does not clear history or reset implementations. The config options clearMocks, mockReset and restoreMocks call them automatically before each test. Since Vitest 5, clearMocks is on by default, while mockReset and restoreMocks stay off, so enable restoreMocks: true (or restore in afterEach) when tests spy on shared objects.
Hazırlıq, təmizləmə və testlərin təcridi
Hər test tək, birinci və ya sonuncu işləməsindən asılı olmayaraq eyni nəticəni verməlidir. Dəyişkən state-i paylaşan testlər sıralarından asılı olaraq keçir və ya uğursuz olur:
// ✗ bütün fayl üçün bir səbət
const cart = createCart();
test("adds an item", () => {
cart.add(tea);
expect(cart.count()).toBe(1);
});
test("starts empty", () => {
expect(cart.count()).toBe(0);
});İkinci test birincidən sonra uğursuz olur, tək işə salınanda isə keçir. Hər test üçün təzə state yarat, testin içində və ya hook-da:
let cart: Cart;
beforeEach(() => {
cart = createCart();
});Vitest hook-ları cari fayla, describe blokunun içində elan olunanda isə həmin bloka aiddir: beforeEach və afterEach hər testin ətrafında, beforeAll və afterAll isə hamısının ətrafında bir dəfə işləyir. afterEach test uğursuz olanda da işləyir, ona görə təmizləmənin yeri oradır. beforeEach təmizləmə funksiyası da qaytara bilər; Vitest onu testdən sonra, afterEach hook-larından da sonra işə salır və beləliklə hazırlıq və təmizləmə yan-yana qalır. onTestFinished(fn) isə təmizləməni testin öz içindən qeydə alır.
beforeEach(() => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
return () => spy.mockRestore();
});Vitest nəyi təcrid edir, nəyi etmir
- Test faylları default olaraq ayrı mühitlərdə işləyir (
isolate: true), ona görə bir faylın modul state-i digərinə keçmir. - Eyni fayldakı testlər modul səviyyəsindəki dəyişənləri,
globalThis-i, simulyasiya olunmuş DOM-u və restore olunmamış hər spy-ı paylaşır. Vitest onları yazıldıqları sıra ilə işə salır və bu, sıradan asılılığı gizlədir: yalnız başqa testdən sonra keçən test kimsə onu tək işə salana və ya sıranı--sequence.shuffleilə qarışdırana qədər keçməyə davam edir. - Mock çağırışlarının tarixçəsi Vitest 5-dən bəri hər testdən əvvəl silinir (
clearMocks: true), ona görətoHaveBeenCalledTimes(1)yalnız cari testin çağırışlarını sayır.mockReturnValueilə verilmiş implementasiyalarmockResetaktiv deyilsə qalır, spy qoyulmuş metodlar isərestoreMocksaktiv deyilsə əvəz olunmuş qalır.
beforeAll-u testlərin yalnız oxuduğu baha hazırlıq üçün saxla; testin dəyişdiyi hər şey həmin test üçün yaradılmalıdır. Eyni qayda yaddaşdan kənarda da keçərlidir: eyni müvəqqəti fayla, verilənlər bazasının eyni sətirlərinə və ya eyni porta yazan testlər bir-birindən asılıdır və Vitest faylları paralel işə salanda toqquşa bilər.
Every test should give the same result whether it runs alone, first or last. Tests that share mutable state pass or fail depending on their order:
// ✗ one cart for the whole file
const cart = createCart();
test("adds an item", () => {
cart.add(tea);
expect(cart.count()).toBe(1);
});
test("starts empty", () => {
expect(cart.count()).toBe(0);
});The second test fails after the first, and passes when run alone. Create fresh state for every test, inside the test or in a hook:
let cart: Cart;
beforeEach(() => {
cart = createCart();
});Vitest's hooks apply to the current file, or to the current describe block when declared inside one: beforeEach and afterEach run around every test, beforeAll and afterAll once around all of them. afterEach runs even when the test failed, so clean-up belongs there. beforeEach may also return a clean-up function, which Vitest runs after the test, after the afterEach hooks; that keeps setup and teardown side by side. onTestFinished(fn) registers clean-up from inside the test itself.
beforeEach(() => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
return () => spy.mockRestore();
});What Vitest isolates, and what it doesn't
- Test files run in separate environments by default (
isolate: true), so module state from one file doesn't leak into another. - Tests in the same file share module-level variables,
globalThis, the simulated DOM and any spy that wasn't restored. Vitest runs them in the order they are written, which hides order dependence: a test that only passes after another one keeps passing until someone runs it alone or shuffles the order with--sequence.shuffle. - Mock call history is cleared before each test since Vitest 5 (
clearMocks: true), sotoHaveBeenCalledTimes(1)counts only the current test's calls. Implementations set withmockReturnValueare kept unlessmockResetis on, and spied methods stay replaced unlessrestoreMocksis on.
Keep beforeAll for expensive setup that tests only read; anything a test changes should be created for that test. The same applies outside memory: tests that write to the same temporary file, database rows or port depend on each other and can collide when Vitest runs files in parallel.
Həddindən artıq mock
Double asılılığın davranışını testdən çıxarır. Kent C. Dodds Write tests. Not too many. Mostly integration. məqaləsində xəbərdarlıq edir: "Nəyisə mock edəndə test etdiyin şeylə mock olunan şey arasındakı inteqrasiyaya olan bütün əminliyi aradan qaldırırsan." Hər yerdə istifadə olunan double-lar məhsul sınıq olanda da yaşıl qalan testlər yaradır.
vi.mock("./cart-store");
vi.mock("./pricing");
vi.mock("./orders-api");
test("checkout", async () => {
vi.mocked(loadCart).mockResolvedValue(cart);
vi.mocked(calculateTotal).mockReturnValue(42);
await checkout("c1");
expect(loadCart).toHaveBeenCalledWith("c1");
expect(calculateTotal).toHaveBeenCalledWith(cart);
expect(submitOrder).toHaveBeenCalledWith({ cartId: "c1", total: 42 });
});Bu test implementasiyanı sətir-sətir təkrarlayır. Kod yenidən təşkil olunanda (qiymət hesablaması iki funksiyaya bölünəndə) sınır, calculateTotal səhv rəqəm qaytaranda isə keçir, çünki 42 sadəcə testin dediyi rəqəmdir.
Həddindən artıq mock-un əlamətləri:
- assertion-ların çoxu layihənin öz modulları üzərində
toHaveBeenCalledWith-dir; - stub-ların qaytardığı dəyərlər real asılılığın qaytardığından götürülmür, uydurulur və zaman keçdikcə ondan uzaqlaşır.
Nəyi əvəz etməli
Fowler iki üslubu təsvir edir. Klassik üslub "mümkünsə real obyektlərdən, real olandan istifadə etmək çətindirsə double-dan" istifadə edir; mockist üslubun tərəfdarı isə "maraqlı davranışı olan istənilən obyekt üçün həmişə mock-dan istifadə edəcək". Dodds eyni məqalədə "bu qədər çox şeyi mock etməyi dayandırmağı" daha çox inteqrasiya testi yazmaq üçün edə biləcəyin ən böyük addım adlandırır. Praktikada bu, öz modullarını (qiymət hesablaması, formatlama, reducer-lər, store) real saxlamaq və yavaş, deterministik olmayan və ya sənin prosesindən kənarda olanı əvəz etmək deməkdir: şəbəkəni, saatı, təsadüfiliyi, üçüncü tərəf SDK-larını. Əvəz edəndə sərhəddə əvəz et: kodunun hamısı fake HTTP qatı ilə real qatla işlədiyi kimi işləyir, öz fetch wrapper-inin stub-ı isə wrapper-in məntiqini ötürüb keçir.
Injection, yoxsa vi.mock?
vi.mock(path, factory?) test faylında modulu onu import edən hər yer üçün əvəz edir. Vitest bu çağırışı import-ların üstünə qaldırır (hoisting), Vitest 5-dən bəri isə çağırış faylın ən üst səviyyəsində deyilsə, xəta atır. Test olunan kodu dəyişmədən işləyir, ona görə ondan həddindən artıq istifadə etmək asandır: asılılıq kodda görünmür və əvəzetmə bütün fayla aiddir.
Ötürülən asılılıqlar (parametrlər, props, context) açıqdır və hər test üçün ayrıca seçilir. Praktik bölgü: sənə məxsus olanı və testdən testə dəyişəni parametr kimi ötür; vi.mock-u asanlıqla ötürülə bilməyən şeylər üçün saxla, məsələn, ağacın dərinliyində import olunan üçüncü tərəf modulu və ya import zamanı yan təsiri olan modul üçün.
A double removes a dependency's behaviour from the test. Kent C. Dodds warns in Write tests. Not too many. Mostly integration.: "When you mock something you're removing all confidence in the integration between what you're testing and what's being mocked." Used everywhere, doubles produce tests that stay green while the product is broken.
vi.mock("./cart-store");
vi.mock("./pricing");
vi.mock("./orders-api");
test("checkout", async () => {
vi.mocked(loadCart).mockResolvedValue(cart);
vi.mocked(calculateTotal).mockReturnValue(42);
await checkout("c1");
expect(loadCart).toHaveBeenCalledWith("c1");
expect(calculateTotal).toHaveBeenCalledWith(cart);
expect(submitOrder).toHaveBeenCalledWith({ cartId: "c1", total: 42 });
});This test restates the implementation line by line. It breaks when the code is reorganised (pricing split into two functions) and passes when calculateTotal returns a wrong number, because 42 is whatever the test said.
Signs of over-mocking:
- most assertions are
toHaveBeenCalledWithon the project's own modules; - stubbed return values are invented rather than taken from what the real collaborator returns, and drift from it over time.
What to replace
Fowler describes two styles. The classical one uses "real objects if possible and a double if it's awkward to use the real thing"; the mockist one "will always use a mock for any object with interesting behavior". Dodds, in the same article, calls "stop mocking so much stuff" the biggest thing you can do to write more integration tests. In practice that means keeping your own modules real (pricing, formatting, reducers, the store) and replacing what is slow, non-deterministic or outside your process: the network, the clock, randomness, third-party SDKs. When you do replace, replace at the boundary: a fake HTTP layer is used by all of your code the same way the real one is, while a stub of your own fetch wrapper skips the wrapper's logic.
Injection or vi.mock?
vi.mock(path, factory?) swaps a module for every importer in the test file. Vitest hoists the call above the imports, and since Vitest 5 it throws if the call is not at the top level of the file. It works without changing the code under test, which is why it is easy to overuse: the dependency is invisible in the code and the replacement applies to the whole file.
Injected dependencies (parameters, props, context) are explicit and chosen per test. A practical split: inject what you own and what varies between tests; use vi.mock for what can't easily be passed in, such as a third-party module imported deep in the tree or a module with side effects on import.
Snapshot testlər və onların hüdudları
expect(value).toMatchSnapshot() dəyəri serializasiya edir və testin ilk işləməsində saxlanmış nüsxə ilə müqayisə edir; nüsxə testin yanındakı __snapshots__/<file>.snap faylında olur. toMatchInlineSnapshot() həmin nüsxəni test faylının özünə yazır və kiçik snapshot-ları yoxlandıqları yerdə görünən saxlayır.
test("formats a receipt", () => {
expect(formatReceipt(order)).toMatchSnapshot();
});Sonrakı run-larda istənilən fərq testi diff ilə uğursuz edir. Dəyişiklik qəsdəndirsə, saxlanmış nüsxəni vitest -u ilə və ya watch rejimində u düyməsi ilə yenilə. CI-da Vitest snapshot-ları heç vaxt yazmır, ona görə əskik, dəyişmiş və ya köhnəlmiş (obsolete) snapshot run-ı uğursuz edir. Snapshot faylları koddur: dəyişikliklə birlikdə commit və review olunur.
Snapshot-lar harada kömək edir
- təsadüfən dəyişməməli olan böyük, strukturlu çıxış: serializer, generasiya olunmuş konfiqurasiya, formatlanmış xəta mesajı, CLI-ın çıxışı;
- testsiz kodu refaktorinq etməzdən əvvəl təhlükəsizlik toru: cari çıxışı qeydə al, refaktorinq et, heç nəyin dəyişmədiyini təsdiqlə.
Onların hüdudları
- Snapshot kodun nə etməli olduğunu yox, nə etdiyini qeydə alır. İlk run nə çıxsa qəbul edir, bug-lar da daxil. Kimsə saxlanmış dəyəri oxuyub onun düzgün olduğunu təsdiqləməlidir.
- Böyük snapshot-lar baxılmadan təsdiqlənir. Səhifənin 300 sətirlik snapshot-u hər markup dəyişikliyində dəyişəndə review edənlər diff-i oxumağı dayandırır. Vitest guide-ı xəbərdarlıq edir ki, sınıq çıxışı "kor-koranə
ubasaraq" qəbul etmək asandır. - Default olaraq implementasiya detallarını test edirlər. Wrapper elementlər, class adları və atributların sırası davranış dəyişmədən dəyişir, ona görə bütöv komponentin snapshot-ları zərərsiz refaktorinqlərdə sınır və insanları baxmadan yeniləməyə öyrəşdirir.
- Dinamik dəyərlər (tarixlər, generasiya olunan id-lər) hər run-da fərqlənir.
toMatchSnapshot({ id: expect.any(Number) })kimi property matcher-lər formanı sabitləyir, dəyəri isə nəzərə almır.
Vitest guide-ının qaydası: "çıxışda istənilən dəyişiklikdən qorunmaq istəyəndə snapshot-lardan, yalnız konkret xüsusiyyətlər vacib olanda isə hədəfli assertion-lardan istifadə et." Komponent üçün istifadəçinin gördüyü mətnə və ya role-a yazılmış assertion vacib olanı ifadə edir; bütöv markup-ın snapshot-u isə hər şeyi ifadə edir, yəni vacib olan barədə heç nə demir.
Pull request-dəki istənilən snapshot üçün faydalı review sualı: bu diff bug olsaydı, review edən onu görərdimi? Görməzdisə, snapshot-u bir neçə hədəfli assertion ilə əvəz et.
expect(value).toMatchSnapshot() serialises the value and compares it with the copy saved the first time the test ran, in a __snapshots__/<file>.snap file next to the test. toMatchInlineSnapshot() writes that copy into the test file itself, which keeps small snapshots visible where they are checked.
test("formats a receipt", () => {
expect(formatReceipt(order)).toMatchSnapshot();
});On later runs any difference fails the test with a diff. If the change is intended, update the stored copy with vitest -u or the u key in watch mode. In CI Vitest never writes snapshots, so a missing, changed or obsolete one fails the run. Snapshot files are code: they are committed and reviewed with the change.
Where snapshots help
- large, structured output that must not change by accident: a serializer, generated configuration, a formatted error message, a CLI's output;
- a safety net before refactoring code without tests: record the current output, refactor, confirm nothing changed.
Their limits
- A snapshot records what the code does, not what it should do. The first run accepts whatever comes out, bugs included. Someone has to read the stored value and confirm it is right.
- Large snapshots get rubber-stamped. When a 300-line snapshot of a page changes with every markup tweak, reviewers stop reading the diff. The Vitest guide warns that it is easy to accept a broken output "by blindly pressing
u". - They test implementation details by default. Wrapper elements, class names and attribute order change without any change in behaviour, so whole-component snapshots break on harmless refactors and teach people to update without looking.
- Dynamic values (dates, generated ids) differ on every run. Property matchers such as
toMatchSnapshot({ id: expect.any(Number) })pin the shape and ignore the value.
The Vitest guide's rule: "use snapshots when you want to protect against any change in the output, and use targeted assertions when you only care about specific properties." For a component, an assertion on the text or the role the user sees states what matters; a snapshot of the whole markup states everything, so it says nothing about what matters.
A useful review question for any snapshot in a pull request: if this diff had been a bug, would the reviewer have noticed? If not, replace the snapshot with a few targeted assertions.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Unit test kodu seçilmiş girişlərlə çağırır və çıxışları yoxlayır. Ən asan test olunan kod təmiz funksiyalardır, ona görə biznes qaydalarını komponentlərdən kənarda saxlayıram. Asılılıqlar üçün test double-lardan istifadə edirəm; Gerard Meszaros onları dummy, stub, spy, mock və fake növlərinə bölür, Vitest-də isə bu, əsasən vi.fn və vi.spyOn-dur. Real asılılıqlara və fake-lərə üstünlük verirəm, yalnız yavaş və ya deterministik olmayanı əvəz edirəm, imkan olanda modulları mock etmək əvəzinə asılılıqları ötürürəm, hər testdən sonra spy-ları restore edirəm və çağırışın özü davranış deyilsə, çağırışları yox, nəticələri yoxlayıram."
Gözlənilən suallar
toBe,toEqual, yoxsatoStrictEqual?Object.isilə eynilik;undefinedaçarlara və class tiplərinə baxmayan rekursiv bərabərlik; onları da yoxlayan rekursiv bərabərlik.- Stub ilə mock arasında fərq nədir? Stub hazır cavablar qaytarır və sən nəticəni yoxlayırsan (state verification); mock isə alacağı çağırışlar barədə gözləntilər daşıyır (behaviour verification). Əsas mənbə Martin Fowler-in Mocks Aren't Stubs məqaləsidir.
vi.fn, yoxsavi.spyOn? Yeni funksiya, yoxsa mövcud metodun ətrafında, sən əvəz edənə qədər orijinalı çağırmağa davam edən wrapper.mockClear,mockReset,mockRestore? Tarixçə; tarixçə və implementasiya; bunların hamısı üstəgəl spy-lar üçün orijinal metodun geri qaytarılması.Date.now()və yaMath.random()-dan istifadə edən kodu necə test edirsən? Saatı və ya təsadüfi dəyər mənbəyini parametr kimi ötür, vaxt üçün isə Vitest-in fake timer-lərindən vəvi.setSystemTime-dan istifadə et.
Bal itirməyə səbəb olan səhvlər
- Hər double-a mock demək və hər yerdə çağırışları yoxlamaq.
expect(() => fn()).toThrow()əvəzinəexpect(fn()).toThrow()yazmaq..rejectsvə ya.resolves-uawaitetməmək.- Paylaşılan obyektə spy qoyub onu restore etməmək.
- Test olunan modulu və ya layihənin öz təmiz modullarını mock etmək.
Senior səviyyəni göstərən məqamlar
Alətlərdən yox, test oluna bilən dizayndan danış: nazik qabıqlı təmiz nüvə, parametr kimi ötürülən asılılıqlar və yalnız nəzarət etmədiyin sərhədlərdə double-lar. Altı mock-u olan testi dizayn problemi əlaməti kimi oxuduğunu və son dəyişiklikləri bildiyini göstər, məsələn, Vitest 5-in default olaraq hər testdən əvvəl mock tarixçəsini sildiyini və await olunmamış asinxron assertion-ları uğursuz etdiyini.
A 30-second answer. "A unit test calls code with chosen inputs and checks the outputs. Pure functions are the easiest to test, so I keep business rules out of components. For dependencies I use test doubles, which Gerard Meszaros divides into dummies, stubs, spies, mocks and fakes; in Vitest that is mostly vi.fn and vi.spyOn. I prefer real collaborators and fakes, replace only what is slow or non-deterministic, inject dependencies where I can instead of mocking modules, restore spies after each test, and assert on results rather than calls unless the call is the behaviour."
Questions you are likely to get
toBe,toEqualortoStrictEqual? Identity byObject.is; recursive equality that ignoresundefinedkeys and class types; recursive equality that checks them.- What is the difference between a stub and a mock? A stub returns canned answers and you check the result (state verification); a mock carries expectations about the calls it receives (behaviour verification). Martin Fowler's Mocks Aren't Stubs is the reference.
vi.fnorvi.spyOn? A new function versus a wrapper around an existing method that still calls the original until you replace it.mockClear,mockReset,mockRestore? History; history and implementation; all of that plus the original method back for spies.- How do you test code that uses
Date.now()orMath.random()? Inject a clock or a random source, or use Vitest's fake timers andvi.setSystemTimefor time.
Mistakes that cost points
- Calling every double a mock and asserting on calls everywhere.
expect(fn()).toThrow()instead ofexpect(() => fn()).toThrow()..rejectsor.resolveswithoutawait.- Spying on a shared object without restoring it.
- Mocking the module under test, or the project's own pure modules.
Senior signal
Talk about design for testability rather than tools: a pure core with a thin shell, dependencies passed in, and doubles only at boundaries you don't control. Show that you read a test with six mocks as a design smell, and that you know what changed recently, for example that Vitest 5 clears mock history before each test by default and fails unawaited asynchronous assertions.
Unit testləri və mock-ları review edərkən nəyi yoxlamalı
Özün yazmadığın unit testləri, məsələn, komanda yoldaşının pull request-ində və ya generasiya olunmuş kodda review edəndə bu siyahıdan istifadə et. Testlərdəki və double-lardakı səhvlər uğursuzluq kimi görünmür; sonradan "test olunmuş" bug-lar və hər refaktorinqdə sınan testlər kimi üzə çıxır.
- Test olunan kod realdırmı, yalnız asılılıqları əvəz olunubmu? Test olunan funksiyanın import-unu tap və heç bir
vi.mockvə yavi.spyOn-un onu əvəz etmədiyinə əmin ol; nəticəsini yoxladığı funksiyanın özünü stub edən test yalnız stub-ı test edir. - Assertion-lar nəticəni yoxlayır, yoxsa yalnız double-ların çağırıldığını? Çağırış nəticənin özüdürsə (göndərilən event, dəyərlərlə çağırılan
onSubmit),toHaveBeenCalledWithyerindədir; bütün assertion-lar layihənin öz modullarına çağırış yoxlamasıdırsa, test implementasiyanı təkrarlayır və səhv dəyərləri buraxır. - Düzgün bərabərlik seçilibmi? Obyektlərdə
toBeeyniliyi yoxlayır və bərabər nüsxələrdə uğursuz olur;toEqualundefinedaçarlara və class tiplərinə baxmır, ona görə dəqiq forma vacib olandatoStrictEqual, kəsr ədədlər üçüntoBeCloseToyaz. - Xətalar və promise-lər düzgün yoxlanılırmı?
toThrowfunksiya tələb edir,expect(() => fn()).toThrow("message"), və mesajı yoxlamalıdır;.resolvesvə.rejectsawaitolunmalıdır, olunmasa, Vitest 5 testi uğursuz edir. - Hər spy restore olunurmu və hər test müstəqildirmi?
console-a və ya başqa paylaşılan obyektə qoyulmuşvi.spyOnüçünmockRestore(),restoreMocks: truevə yaafterEach-də təmizləmə lazımdır, testlər arasında paylaşılan state isəbeforeEachtələb edir. Sıradan asılılığı üzə çıxarmaq üçün faylı--sequence.shuffleilə işə sal. - Stub-ların dəyərləri real asılılığın qaytardığına uyğundurmu? Uydurulmuş forma (real API
{ unitPrice }qaytaranda{ price }) testlərin əslində mövcud olmayan müqaviləyə görə keçməsinə imkan verir; double-ıvi.fn<typeof realFn>()və yavi.mocked()ilə tiplə ki, TypeScript bu uyğunsuzluğu tutsun. - Hər snapshot kiçik, düzgün və izah olunubmu? Snapshot kodun ilk run-da çıxardığı hər şeyi qəbul edir, ona görə saxlanmış dəyəri oxu və diff-dəki hər yenilənmiş snapshot-un niyə dəyişdiyini soruş.
Use this list when you review unit tests you did not write yourself, in a teammate's pull request or in generated code. Mistakes in tests and doubles don't show up as failures; they show up later as bugs that were "tested" and as tests that break on every refactor.
- Is the code under test real, with only its collaborators replaced? Find the import of the tested function and make sure no
vi.mockorvi.spyOnreplaces it; a test that stubs the very function whose result it asserts only tests the stub. - Do the assertions check results, or only that doubles were called?
toHaveBeenCalledWithfits when the call is the outcome (an event sent,onSubmitcalled with the values); when every assertion is a call check on the project's own modules, the test restates the implementation and misses wrong values. - Is the right equality used?
toBeon objects checks identity and fails on equal copies;toEqualignoresundefinedkeys and class types, so usetoStrictEqualwhere the exact shape matters andtoBeCloseTofor floating-point numbers. - Are errors and promises asserted correctly?
toThrowneeds a function,expect(() => fn()).toThrow("message"), and should check the message;.resolvesand.rejectsmust be awaited, and Vitest 5 fails the test when they are not. - Is every spy restored and every test independent? A
vi.spyOnonconsoleor another shared object needsmockRestore(),restoreMocks: trueor clean-up inafterEach, and state shared between tests needs abeforeEach. Run the file with--sequence.shuffleto expose order dependence. - Do stubbed values match what the real collaborator returns? An invented shape (
{ price }where the real API returns{ unitPrice }) lets tests pass against a contract that doesn't exist; type the double withvi.fn<typeof realFn>()orvi.mocked()so TypeScript catches the drift. - Is each snapshot small, correct and explained? A snapshot accepts whatever the code produced on its first run, so read the stored value, and ask why every updated snapshot in the diff changed.