Şəbəkəni və modulları mock etmək
Sonda öz mock-larını test etməyə başlamadan şəbəkəni və modulları necə saxtalaşdırmalı: seam seçimi, Mock Service Worker handler-ləri və loading və xəta vəziyyətləri üçün hər testə aid override-lar, fetch-i stub etməyin qiyməti, vi.mock-un yuxarı qaldırılması və qismən mock-lar, ES modullarının spy üçün məhdudiyyətləri və contract drift.
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 Middle səviyyəsindən başlayır.
Seam seçimi: harada mock etməli
real bir şeyi əvəz edir, testin real kodu kəsdiyi yerə isə seam deyilir. Data yükləyən kodda üç tipik seam var:
TaskList → useTasks() → api.getTasks() → fetch() → network → server
1. vi.mock("./api") replaces api.getTasks()
2. vi.stubGlobal("fetch") replaces fetch()
3. an MSW handler replaces the server's answerSeam nə qədər aşağıdadırsa, testdə sənin kodunun o qədər çox hissəsi işləyir. Öz api modulunu mock etsən (birinci seam), test URL-i quran, header-ləri təyin edən, body-ni serializasiya edən, response.ok-u yoxlayan, JSON-u parse edən və uğursuzluqları xətaya çevirən kodu heç vaxt işə salmır, halbuki səhvin ən çox ehtimal olunduğu yer məhz bu koddur. Üstəlik, wrapper-i refaktor edəndə (getTasks-ın adını dəyişəndə, arqumentlərini dəyişəndə) ekran əvvəlki kimi işləsə də test sınır.
Şəbəkə sərhədində mock etmək (üçüncü seam) yalnız həqiqətən tətbiqdən kənarda olanı əvəz edir: serveri. Komponent, hook, wrapper və real fetch hamısı işləyir; test yalnız serverin nə cavab verəcəyini həll edir. Eyni sorğuları və eyni UI-ı saxlayan refaktorinq testləri yaşıl saxlayır. Mock Service Worker (MSW) məhz bunun üçün yaradılıb, Vitest-in bələdçisi də sorğuları mock etmək üçün onu tövsiyə edir.
Sadə qayda: sənə aid olmayanı sənin koduna daxil olduğu nöqtədə mock et. HTTP üçün bu nöqtə sənin fetch ətrafındakı öz wrapper-in yox, kodundan çıxan sorğunun özüdür.
Asılılıq test etdiyin şəbəkə deyilsə, yenə düzgün alətdir:
- testdə istəmədiyin yan təsirləri olan SDK: analitika, xəta hesabatları, ödəniş vidjeti;
- ağır və ya jsdom-da işləməyən kitabxana: xəritə, WebGL qrafiki;
- testin idarə etməli olduğu dəyər: feature flag client-i, ID generatoru.
Seam qırmızı testin nə demək olduğunu da müəyyən edir. Şəbəkə səviyyəsindəki test sınanda istifadəçinin görə biləcəyi davranış dəyişib. Öz modulunu mock edən test sınanda isə çox vaxt yalnız sənin iki faylın arasındakı çağırış dəyişib.
Qlobal fetch-i stub etmək (ikinci seam) ortada dayanır: wrapper-in işləyir, amma onun fetch-i necə çağırdığı dondurulur. Bunun qiyməti vi.stubGlobal bölməsində sadalanır.
A replaces something real, and the place where the test cuts the real code off is the seam. For code that loads data there are three common seams:
TaskList → useTasks() → api.getTasks() → fetch() → network → server
1. vi.mock("./api") replaces api.getTasks()
2. vi.stubGlobal("fetch") replaces fetch()
3. an MSW handler replaces the server's answerThe lower the seam, the more of your own code runs in the test. Mock your api module (seam 1) and the test never runs the code that builds the URL, sets headers, serialises the body, checks response.ok, parses JSON and turns failures into errors, which is the code most likely to be wrong. The test also breaks when you refactor the wrapper (rename getTasks, change its arguments) although the screen behaves exactly as before.
Mocking at the network boundary (seam 3) replaces only what is really outside your app: the server. The component, the hook, the wrapper and the real fetch all run; the test only decides what the server answers. A refactor that keeps the same requests and the same UI keeps the tests green. This is what Mock Service Worker (MSW) is built for, and it is what Vitest's guide recommends for mocking requests.
A rule of thumb: mock what you do not own, at the point where it enters your code. For HTTP that point is the request leaving your code, not your own wrapper around fetch.
A is still the right tool when the dependency is not the network you are testing:
- an SDK with side effects you do not want in a test: analytics, error reporting, a payment widget;
- a library that is heavy or does not work in jsdom: a map, a WebGL chart;
- a value the test must control: a feature-flag client, an ID generator.
The seam also decides what a red test means. When a network-level test fails, behaviour the user can see has changed. When a test that mocks your own module fails, often only the call between two of your files has changed.
Stubbing the global fetch (seam 2) sits in between: it runs your wrapper, but it freezes the way the wrapper calls fetch. Its costs are listed in the section on vi.stubGlobal.
Mock Service Worker: handler-lər və test serveri
MSW serverin cavablarını request handler-lər kimi təsvir edir: HTTP metodu, URL şablonu və cavab qaytaran resolver funksiyası.
// src/mocks/handlers.ts
import { http, HttpResponse } from "msw/http";
export const API = "https://api.example.com";
export const handlers = [
http.get(`${API}/tasks`, () => {
return HttpResponse.json([
{ id: "t1", title: "Write the release notes", done: false },
{ id: "t2", title: "Review the login page", done: true },
]);
}),
http.post(`${API}/tasks`, async ({ request }) => {
const body = (await request.json()) as { title?: string };
if (!body.title) {
return HttpResponse.json({ message: "Title is required" }, { status: 400 });
}
return HttpResponse.json({ id: "t3", title: body.title, done: false }, { status: 201 });
}),
];Resolver real Request-i (request), path parametrlərini (params, /tasks/:id kimi şablon üçün) və cookies-i alır. HttpResponse.json(body, init) JSON body-li cavab qurur; init Response konstruktorunda olduğu kimi status və headers qəbul edir.
Vitest-də (Node) handler-ləri msw/node-dan gələn setupServer işə salır. Adına baxmayaraq, o, heç bir port açmır: test prosesinin daxilində çıxan sorğuları tutur, ona görə sənin kodunun real fetch çağırışı işləyir və handler-in cavabını alır.
// src/mocks/node.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);// vitest.setup.ts (test.setupFiles-da göstərilib)
import "@testing-library/jest-dom/vitest";
import { afterAll, afterEach, beforeAll } from "vitest";
import { server } from "./src/mocks/node";
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());listen()sorğuların tutulmasını başladır,close()isə dayandırır.resetHandlers()testinserver.use()ilə əlavə etdiyi handler-ləri silir və ilkin siyahını saxlayır.onUnhandledFrame: "error"heç bir handler-ə uyğun gəlməyən sorğu üçün xəta yazır və sorğunu dayandırır. Default dəyər olan"warn"isə xəbərdarlıq yazıb sorğunu buraxır, ona görə URL-dəki bir hərf səhvi testi səssizcə real serverə göndərə bilər.
Bunlar MSW 3-ün adlarıdır. MSW 2 http və HttpResponse-u msw-dan export edirdi, seçimin adı isə onUnhandledRequest idi; MSW 3 onun adını dəyişdi, çünki o, indi WebSocket bağlantılarını da əhatə edir.
Brauzerdə eyni handler-lər msw/browser-dən gələn setupWorker vasitəsilə işləyir; o, Service Worker qeydiyyata alır (npx msw init <PUBLIC_DIR> --save onun skriptini public qovluğuna kopyalayır). Bu, hələ hazır olmayan API ilə lokal development, Storybook və brauzerdə işləyən test runner-lər üçün yararlıdır. Render-dən əvvəl worker.start()-ı await et, yoxsa ilk sorğular worker hazır olmamış gedə bilər.
MSW describes the server's answers as request handlers: an HTTP method, a URL pattern and a resolver function that returns a response.
// src/mocks/handlers.ts
import { http, HttpResponse } from "msw/http";
export const API = "https://api.example.com";
export const handlers = [
http.get(`${API}/tasks`, () => {
return HttpResponse.json([
{ id: "t1", title: "Write the release notes", done: false },
{ id: "t2", title: "Review the login page", done: true },
]);
}),
http.post(`${API}/tasks`, async ({ request }) => {
const body = (await request.json()) as { title?: string };
if (!body.title) {
return HttpResponse.json({ message: "Title is required" }, { status: 400 });
}
return HttpResponse.json({ id: "t3", title: body.title, done: false }, { status: 201 });
}),
];The resolver receives the real Request (request), the path parameters (params, for a pattern like /tasks/:id) and cookies. HttpResponse.json(body, init) builds a response with a JSON body; init takes status and headers, like the Response constructor.
In Vitest (Node), setupServer from msw/node turns the handlers on. Despite the name it opens no port: it intercepts outgoing requests inside the test process, so your code's real fetch call runs and receives the handler's response.
// src/mocks/node.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);// vitest.setup.ts (listed in test.setupFiles)
import "@testing-library/jest-dom/vitest";
import { afterAll, afterEach, beforeAll } from "vitest";
import { server } from "./src/mocks/node";
beforeAll(() => server.listen({ onUnhandledFrame: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());listen()starts the interception andclose()stops it.resetHandlers()removes the handlers a test added withserver.use()and keeps the initial list.onUnhandledFrame: "error"prints an error and stops a request that no handler matches. The default,"warn", prints a warning and lets the request through, so a typo in a URL can quietly send a test to a real server.
These are MSW 3's names. MSW 2 exported http and HttpResponse from msw and called the option onUnhandledRequest; MSW 3 renamed it because it now also covers WebSocket connections.
In the browser the same handlers run through setupWorker from msw/browser, which registers a Service Worker (npx msw init <PUBLIC_DIR> --save copies its script into your public folder). It serves local development against an unfinished API, Storybook and browser test runners. Await worker.start() before rendering, or the first requests can go out before the worker is ready.
Loading, xəta və yavaş cavabların testi
TaskList ${API}/tasks-ı yükləyir və əvvəlcə role="status" ilə "Loading tasks..." göstərir, sonra siyahını, "No tasks yet." mətnini və ya alert-i. Default handler uğurlu ssenarini əhatə edir; qalan hər vəziyyət üçün bir server.use() çağırışı kifayətdir:
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import { http, HttpResponse } from "msw/http";
import { delay } from "msw/utils/delay";
import { API } from "../mocks/handlers";
import { server } from "../mocks/node";
import { TaskList } from "./TaskList";
test("shows the tasks", async () => {
render(<TaskList />);
expect(await screen.findByText("Write the release notes")).toBeInTheDocument();
});
test("shows the empty state", async () => {
server.use(http.get(`${API}/tasks`, () => HttpResponse.json([])));
render(<TaskList />);
expect(await screen.findByText("No tasks yet.")).toBeInTheDocument();
});
test("shows an error when the server fails", async () => {
server.use(
http.get(`${API}/tasks`, () => HttpResponse.json({ message: "Down" }, { status: 500 })),
);
render(<TaskList />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load tasks");
});
test("shows an error when the network fails", async () => {
server.use(http.get(`${API}/tasks`, () => HttpResponse.error()));
render(<TaskList />);
expect(await screen.findByRole("alert")).toBeInTheDocument();
});
test("keeps the loading state while the server is silent", () => {
server.use(
http.get(`${API}/tasks`, async () => {
await delay("infinite");
return HttpResponse.json([]);
}),
);
render(<TaskList />);
expect(screen.getByRole("status")).toHaveTextContent("Loading tasks");
});server.use()handler-ləri siyahının əvvəlinə əlavə edir, MSW isə cavab qaytaran ilk handler-i işlədir, ona görə override yalnız bu testdə qalib gəlir;afterEach-dəkiresetHandlers()onu silir.{ once: true }seçimi olan handler uyğun gələn bir sorğuya cavab verir, sonra nəzərə alınmır: "ilk sorğu uğursuz olur, təkrar cəhd alınır" ssenarisi üçün əlverişlidir.- 500
fetch-i reject etmir. Promiseresponse.ok === falseilə resolve olur; yalnız şəbəkə xətası reject edir,HttpResponse.error()isəfetch-inTypeErrorilə reject olmasına səbəb olur. Bunlar iki ayrı kod yoludur, ikisini də test et. - Arqumentsiz
delay()brauzerdə realistik təsadüfi müddət gözləyir, Node-da isə testlər sürətli qalsın deyə bu gizli gecikmə ötürülür.delay(ms)dəqiq o qədər gözləyir,delay("infinite")isə heç vaxt cavab vermir.
İstifadəçinin gördüyünü yoxla, "sorğu göndərildi" faktını yox: MSW-nin sənədləri sorğu üzərində assertion-ları implementasiya detalı sayır və tövsiyə etmir. Body vacibdirsə, onu handler-də yoxla və POST /tasks handler-i kimi 400 qaytar; səhv body o zaman ekranda görünür.
TaskList fetches ${API}/tasks and shows "Loading tasks..." with role="status", then the list, "No tasks yet." or an alert. The default handler covers the happy path; every other state is one server.use() call away:
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import { http, HttpResponse } from "msw/http";
import { delay } from "msw/utils/delay";
import { API } from "../mocks/handlers";
import { server } from "../mocks/node";
import { TaskList } from "./TaskList";
test("shows the tasks", async () => {
render(<TaskList />);
expect(await screen.findByText("Write the release notes")).toBeInTheDocument();
});
test("shows the empty state", async () => {
server.use(http.get(`${API}/tasks`, () => HttpResponse.json([])));
render(<TaskList />);
expect(await screen.findByText("No tasks yet.")).toBeInTheDocument();
});
test("shows an error when the server fails", async () => {
server.use(
http.get(`${API}/tasks`, () => HttpResponse.json({ message: "Down" }, { status: 500 })),
);
render(<TaskList />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load tasks");
});
test("shows an error when the network fails", async () => {
server.use(http.get(`${API}/tasks`, () => HttpResponse.error()));
render(<TaskList />);
expect(await screen.findByRole("alert")).toBeInTheDocument();
});
test("keeps the loading state while the server is silent", () => {
server.use(
http.get(`${API}/tasks`, async () => {
await delay("infinite");
return HttpResponse.json([]);
}),
);
render(<TaskList />);
expect(screen.getByRole("status")).toHaveTextContent("Loading tasks");
});server.use()prepends handlers, and MSW uses the first handler that returns a response, so the override wins for this test only;resetHandlers()inafterEachremoves it. A handler with{ once: true }answers one matching request and is then ignored: handy for "the first request fails, the retry succeeds".- A 500 does not reject
fetch. The promise resolves withresponse.ok === false; only a network error rejects, andHttpResponse.error()makesfetchreject with aTypeError. These are two code paths, so test both. delay()without an argument waits a realistic random time in the browser, but in Node that implicit delay is skipped to keep tests fast.delay(ms)waits exactly that long, anddelay("infinite")never answers.
Assert on what the user sees, not on "the request was made": MSW's docs discourage request assertions as implementation details. If the body matters, check it in the handler and answer 400, as the POST /tasks handler does; a wrong body then shows up on the screen.
vi.stubGlobal ilə fetch-i stub etmək
MSW-nin tez alternativi fetch-in özünü əvəz etməkdir:
import { afterEach, expect, it, vi } from "vitest";
import { getTasks } from "./api";
afterEach(() => {
vi.unstubAllGlobals();
});
it("loads the tasks", async () => {
const fetchMock = vi.fn(async () =>
Response.json([{ id: "t1", title: "Write the release notes", done: false }]),
);
vi.stubGlobal("fetch", fetchMock);
const tasks = await getTasks();
expect(tasks).toHaveLength(1);
expect(fetchMock).toHaveBeenCalledWith("https://api.example.com/tasks");
});vi.stubGlobal(name, value) qlobal dəyişəni dəyişir: globalThis.fetch-i, jsdom və ya happy-dom altında isə window.fetch-i də. vi.unstubAllGlobals() ilkin dəyərləri bərpa edir, unstubGlobals: true config seçimi isə onu hər testdən əvvəl çağırır. Adi mənimsətmə də (globalThis.fetch = ...) işləyir, amma onda unstubAllGlobals onu bərpa edə bilmir və saxta funksiya fayldakı sonrakı bütün testlərə keçir.
Test keçir, amma indi kodun nə etdiyini yox, fetch-i necə çağırdığını təsvir edir:
- Çağırışın forması dondurulur. Kod ikinci arqument ötürən kimi (header-lər,
AbortSignal),Requestobyekti quran kimi və ya request kitabxanasına keçən kimitoHaveBeenCalledWith(url)sınır, halbuki istifadəçi üçün heç nə dəyişməyib. - Cavab nə yazmısansa, odur. Əllə qurulmuş
{ json: async () => data }-daok,statusvəheadersyoxdur, ona görə xətaların emalı real cavabla olduğu kimi heç vaxt işləmir. Yuxarıdakı kimiResponse.json()heç olmasa realResponsequrur. - Bir stub bütün sorğulara xidmət edir.
/tasksvə/me-ni yükləyən ekrana dəqiq çağırış sırası iləmockResolvedValueOncezənciri lazımdır. İki sorğunun yerini dəyiş, hər biri o birinin body-sini alacaq. - Başqa göndərmə yolları əhatə olunmur.
XMLHttpRequestvə yanavigator.sendBeaconişlədən kod stub-dan yan keçir.
MSW-də bu dörd problemin heç biri yoxdur: handler-lər sorğuya metod və URL üzrə uyğun gəlir, real cavablar qaytarır, hər endpoint-ə ayrıca cavab verir və sorğunun necə göndərildiyi onlar üçün fərq etmir.
vi.stubGlobal şəbəkə olmayan və test mühitində çatışmayan və ya testin idarə etməli olduğu qlobal dəyişənlər üçün düzgün alətdir: jsdom-un implementasiya etmədiyi IntersectionObserver, ResizeObserver və matchMedia, yaxud layout budağı üçün innerWidth. Onu unstubGlobals: true ilə birlikdə işlət ki, hər test real dəyərlərdən başlasın.
The quick alternative to MSW replaces fetch itself:
import { afterEach, expect, it, vi } from "vitest";
import { getTasks } from "./api";
afterEach(() => {
vi.unstubAllGlobals();
});
it("loads the tasks", async () => {
const fetchMock = vi.fn(async () =>
Response.json([{ id: "t1", title: "Write the release notes", done: false }]),
);
vi.stubGlobal("fetch", fetchMock);
const tasks = await getTasks();
expect(tasks).toHaveLength(1);
expect(fetchMock).toHaveBeenCalledWith("https://api.example.com/tasks");
});vi.stubGlobal(name, value) changes a global: globalThis.fetch, and window.fetch under jsdom or happy-dom. vi.unstubAllGlobals() restores the original values, and the unstubGlobals: true config option calls it before each test. A plain assignment (globalThis.fetch = ...) works too, but then unstubAllGlobals cannot restore it, and the fake leaks into every later test in the file.
The test passes, but it now describes how the code calls fetch rather than what the code does:
- The call shape is frozen.
toHaveBeenCalledWith(url)fails as soon as the code passes a second argument (headers, anAbortSignal), builds aRequestobject or moves to a request library, although nothing changed for the user. - The response is whatever you typed. A hand-made
{ json: async () => data }has nook,statusorheaders, so error handling never runs the way it would with a real response.Response.json(), as above, at least builds a realResponse. - One stub serves every request. A screen that loads
/tasksand/meneeds a chain ofmockResolvedValueOncecalls in the exact call order. Reorder two requests and each gets the other's body. - Other ways of sending are not covered. Code that uses
XMLHttpRequestornavigator.sendBeacongoes past the stub.
MSW avoids all four: handlers match by method and URL, answer with real responses, serve each endpoint separately and do not care how the request was made.
vi.stubGlobal is the right tool for globals that are not the network and that the test environment lacks or the test must control: IntersectionObserver, ResizeObserver and matchMedia, which jsdom does not implement, or innerWidth for a layout branch. Pair it with unstubGlobals: true so each test starts from the real values.
vi.mock: modulu əvəz etmək
vi.mock(path, factory?) modulu əvəz edir: həmin yolun hər import-u, həm testdə, həm də test olunan kodda, əvəzedicini alır. Burada completeTask PATCH /tasks/:id göndərir (ona MSW cavab verir) və analitika event-i bildirir; test isə onu real göndərməməlidir:
// tasks.test.ts
import { expect, it, vi } from "vitest";
import { trackEvent } from "./analytics";
import { completeTask } from "./tasks";
vi.mock("./analytics", () => ({
trackEvent: vi.fn(),
}));
it("reports the completed task", async () => {
await completeTask("t1");
expect(trackEvent).toHaveBeenCalledWith("task_completed", { id: "t1" });
});Burada çağırışı yoxlamaq normaldır: analitika event-i ekranda heç nə dəyişməyən birtərəfli yan təsirdir.
Hoisting. vi.mock faylın yuxarısına köçürülür və bütün import-lardan əvvəl işləyir, ona görə onların altında yazılması fərq etmir. Vitest faylın statik import-larını mock-un qeydiyyatını gözləyən dinamik import-lara çevirir. Nəticə: factory özündən kənarda, faylda elan olunmuş dəyişənləri işlədə bilməz, çünki o işləyəndə onlar hələ yoxdur. Ortaq dəyərləri özü də yuxarı qaldırılan vi.hoisted ilə yarat:
const { trackEvent } = vi.hoisted(() => ({ trackEvent: vi.fn() }));
vi.mock("./analytics", () => ({ trackEvent }));Testin, describe-ın və ya funksiyanın içində çağırış yazıldığı yerdə işləməzdi; Vitest 5 belə halda xəta atır (əvvəlki versiyalar yalnız xəbərdarlıq edirdi). Yuxarı qaldırılmayan variant vi.doMock-dur.
Factory-nin qaytardığı obyekt modulun özüdür. Onun buraxdığı export-lar mövcud olmur, default export üçün isə default açarı lazımdır. Factory olmayanda Vitest __mocks__ qovluğundakı eyni adlı faylı işlədir; o da yoxdursa, real modulu avtomatik mock edir: funksiyalar undefined qaytaran mock-a çevrilir, massivlər boşalır, primitivlər olduğu kimi qalır, obyektlər dərin klonlanır.
Qismən mock-lar real modulu saxlayıb bir export-u əvəz edir:
vi.mock(import("./analytics"), async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, trackEvent: vi.fn() };
});Sətir yerinə import("./analytics") ötürmək importOriginal-a modulun tipini verir və factory-nin qaytardığı dəyəri həmin tiplə yoxlayır. vi.importActual(path) real modulu faylın istənilən yerində eyni cür yükləyir. Mock-u hər testdə tiplərlə qurmaq üçün onu bük: vi.mocked(trackEvent).mockReturnValue(...); vi.mocked yalnız tipi dəyişir və eyni funksiyanı qaytarır.
vi.mock(path, factory?) replaces a module: every import of that path, in the test and in the code under test, gets the replacement. Here completeTask sends PATCH /tasks/:id (answered by MSW) and reports an analytics event, which the test must not send for real:
// tasks.test.ts
import { expect, it, vi } from "vitest";
import { trackEvent } from "./analytics";
import { completeTask } from "./tasks";
vi.mock("./analytics", () => ({
trackEvent: vi.fn(),
}));
it("reports the completed task", async () => {
await completeTask("t1");
expect(trackEvent).toHaveBeenCalledWith("task_completed", { id: "t1" });
});Asserting a call is fine here: the analytics event is a one-way side effect with nothing on screen to check.
Hoisting. vi.mock is moved to the top of the file and runs before all imports, so it does not matter that it is written below them. Vitest rewrites the file's static imports into dynamic ones that wait for the mock to be registered. The consequence: the factory cannot use variables declared in the file outside it, because they do not exist yet when it runs. Create shared values with vi.hoisted, which is hoisted as well:
const { trackEvent } = vi.hoisted(() => ({ trackEvent: vi.fn() }));
vi.mock("./analytics", () => ({ trackEvent }));Inside a test, a describe or a function, the call would not run where it is written; Vitest 5 throws an error there (earlier versions only warned). vi.doMock is the variant that is not hoisted.
The factory's object is the module. Exports it leaves out are not there, and a default export needs a default key. Without a factory Vitest uses a file of the same name in a __mocks__ folder; if there is none, it automocks the real module: functions become mocks returning undefined, arrays become empty, primitives stay as they are, objects are deeply cloned.
Partial mocks keep the real module and replace one export:
vi.mock(import("./analytics"), async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, trackEvent: vi.fn() };
});Passing import("./analytics") instead of a string gives importOriginal the module's type and checks the factory's return value against it. vi.importActual(path) loads the real module the same way anywhere in the file. To configure the mock per test with types, wrap it: vi.mocked(trackEvent).mockReturnValue(...); vi.mocked only changes the type and returns the same function.
Testlər arasında sıfırlama
Hər mock state-dir, bir testdən qalan state isə növbəti testi dəyişir. Simptomu: tək işləyəndə keçən, bütün faylla birlikdə isə sınan test, ya da əksinə; sıra dəyişən kimi belə testlər çevrilir. Nə sıza bilər və onu nə sıfırlayır:
- MSW runtime handler-ləri.
server.use()ilə qurulan overrideserver.resetHandlers()-ə qədər qalır;afterEach-də o olmasa, bir testdə qurulan xəta vəziyyətini növbəti test alır. - Stub olunmuş qlobal dəyişənlər.
vi.stubGlobalvi.unstubAllGlobals()-a qədər qalır; ya daunstubGlobals: truetəyin et. - Mock implementasiyaları. Vitest 5 default olaraq hər testdən əvvəl çağırış tarixçəsini təmizləyir (
clearMocksinditrue-dur), ammamockReturnValuevə yamockImplementationilə təyin olunmuş implementasiya qalır.mockReset: truehər testdən əvvəl implementasiyaları sıfırlayır;restoreMocks: truevi.spyOnilə yaradılmış spy-ların orijinallarını geri qaytarır. - Modulların daxilindəki state. Modul hər test faylında bir dəfə icra olunur, ona görə API client-indəki keş, memoize olunmuş istifadəçi və ya ortaq data fetching client-i bir testdən digərinə keçir. Hər test üçün yeni instansiya yarat (singleton əvəzinə factory export et) və ya onu
afterEach-də təmizlə.
Bir config bunların çoxunu bütün fayllar üçün işə salır:
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./vitest.setup.ts"],
mockReset: true,
restoreMocks: true,
unstubGlobals: true,
},
});mockReset aktiv olanda hər mock-un davranışını faylın yuxarısında bir dəfə yox, testin özündə və ya beforeEach-də, ona ehtiyacı olan halın yanında təyin et. Belə oxumaq da asandır: test asılı olduğu cavabı özü göstərir.
Yaxşı yoxlama: bir testi .only ilə tək işə sal, sonra bütün faylı. Nəticələr fərqlənirsə, hansısa state ortaqdır. Onu tap və sıfırla; retry əlavə etmək onu sadəcə gizlədir.
Every mock is state, and state left over from one test changes the next. The symptom is a test that passes alone and fails in the full run, or the reverse; such tests become as soon as the order changes. What can leak, and what resets it:
- MSW runtime handlers. A
server.use()override stays untilserver.resetHandlers(); without it inafterEach, the error state set up in one test is what the next test gets. - Stubbed globals.
vi.stubGlobalstays untilvi.unstubAllGlobals(), or setunstubGlobals: true. - Mock implementations. Vitest 5 clears call history before every test by default (
clearMocksis nowtrue), but an implementation set withmockReturnValueormockImplementationstays.mockReset: trueresets implementations before each test;restoreMocks: trueputs back the originals of spies made withvi.spyOn. - State inside modules. A module is evaluated once per test file, so a cache in your API client, a memoised user or a shared data-fetching client survives from one test to the next. Create a fresh instance per test (export a factory instead of a singleton) or clear it in
afterEach.
One config turns most of this on for every file:
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "jsdom",
globals: true,
setupFiles: ["./vitest.setup.ts"],
mockReset: true,
restoreMocks: true,
unstubGlobals: true,
},
});With mockReset on, set each mock's behaviour in the test or in beforeEach, next to the case that needs it, instead of once at the top of the file. That is also easier to read: the test shows the answer it depends on.
A good check: run a single test with .only, then the whole file. If the results differ, some state is shared. Find it and reset it; adding retries only hides it.
ES modulları, canlı binding-lər və export-lara spy qoymaq
Import surət deyil, export edən modulun dəyişəninə canlı, yalnız oxunan baxışdır (bunu ES modulları mövzusu izah edir). Mock üçün bunun iki nəticəsi vacibdir.
Namespace obyektini dəyişmək olmaz. import * as analytics from "./analytics" xassələrinə yeni dəyər vermək və ya yenidən təyin etmək mümkün olmayan modul namespace obyekti verir; modulun içində analytics.trackEvent = fake TypeError atır. vi.spyOn(analytics, "trackEvent") Vitest-in Node, jsdom və happy-dom mühitlərində yenə işləyir, çünki buna Vitest-in module runner-i icazə verir; sənədlər bunu "zahirən ES Module" olan obyektə spy qoymaq adlandırır və bunun dəyişə biləcəyi barədə xəbərdarlıq edir. Modulların native olduğu Browser Mode-da isə alınmır: namespace "sealed-dir və yenidən konfiqurasiya oluna bilməz". Hər yerdə işləyən forma vi.mock("./analytics", { spy: true })-dur: Vitest modulu avtomatik mock edir, amma hər export-un real implementasiyasını saxlayır, ona görə real kod işləyərkən çağırışları yoxlaya bilirsən.
Eyni modulun içindəki çağırışlar tutulmur.
// analytics.ts
export function trackEvent(name: string, data: object) {
navigator.sendBeacon("/events", JSON.stringify({ name, data }));
}
export function trackTaskCompleted(id: string) {
trackEvent("task_completed", { id });
}trackEvent-ə qoyulan spy və ya mock başqa modulların onu import edəndə gördüyünü dəyişir. trackTaskCompleted isə öz lokal binding-ini birbaşa çağırır, ona görə real funksiyanı çağırmağa davam edir. Vitest-in mocking bələdçisi bu tələni sadalayır: belə funksiyanı kənardan mock etmək mümkün deyil, "çünki ona birbaşa istinad olunur". İki həll yolu:
- əvəz etmək istədiyin funksiyanı ayrıca modula köçür ki, çağıran onu import etsin və
vi.mockonu dəyişə bilsin; - onu parametr kimi ötür (dependency injection):
trackTaskCompleted(id, send = trackEvent), test isə özsend-ini ötürür.
Bütün bunlar vi.mock-a niyə təsir etmir. O, artıq yüklənmiş modulu dəyişmir. Əvəzedicini modul reyestrində heç kim modulu import etməmişdən əvvəl qeydiyyata alır; çağırışın yuxarı qaldırılması və faylın import-larının dinamik import-lara çevrilməsi də buna görədir. Bundan sonra hər import edən əvvəldən əvəzediciyə bağlanır; heç nəyə yeni dəyər vermək lazım olmur.
Bu, tez-tez rast gəlinən bir sürprizi də izah edir: test olunan kod referansı artıq götürübsə (modul səviyyəsində const send = analytics.trackEvent və ya başlanğıcda qeydiyyata alınan callback), sonra yaradılan spy həmin çağırışları görmür. vi.spyOn yalnız spy qurulandan sonra xassə vasitəsilə edilən çağırışları qeydə alır.
An import is a live, read-only view of the exporting module's variable, not a copy (the ES modules topic covers this). Two consequences matter for mocking.
A namespace object cannot be patched. import * as analytics from "./analytics" gives a module namespace object whose properties cannot be reassigned or redefined; analytics.trackEvent = fake throws a TypeError in a module. vi.spyOn(analytics, "trackEvent") still works in Vitest's Node, jsdom and happy-dom environments because Vitest's module runner allows it, on what its docs call "a seemingly ES Module", with a warning that this might change. In Browser Mode, where modules are native, it fails: the namespace "is sealed and can't be reconfigured". The form that works everywhere is vi.mock("./analytics", { spy: true }): Vitest automocks the module but keeps each export's real implementation, so you can assert calls while the real code runs.
Calls inside the same module are not intercepted.
// analytics.ts
export function trackEvent(name: string, data: object) {
navigator.sendBeacon("/events", JSON.stringify({ name, data }));
}
export function trackTaskCompleted(id: string) {
trackEvent("task_completed", { id });
}A spy or a mock of trackEvent changes what other modules see when they import it. trackTaskCompleted calls its own local binding directly, so it keeps calling the real function. Vitest's mocking guide lists this pitfall: such a function cannot be mocked from the outside "because it is referenced directly". Two fixes:
- move the function you want to replace into its own module, so the caller imports it and
vi.mockcan swap it; - pass it in (dependency injection):
trackTaskCompleted(id, send = trackEvent), and the test passes its ownsend.
Why vi.mock is not affected by any of this. It does not patch a module after it is loaded. It registers the replacement in the module registry before anything imports the module, which is why the call is hoisted and the file's imports are rewritten into dynamic ones. Every importer then binds to the replacement from the start; nothing needs to be reassigned.
This also explains a common surprise: a spy created after the code under test captured a reference (const send = analytics.trackEvent at module level, or a callback registered at startup) does not see those calls. vi.spyOn only records calls made through the property after the spy was installed.
Modul mock-unu hər testdə dəyişmək
vi.mock hər faylda bir dəfə, import-lardan əvvəl işləyir. Ehtiyacların çoxunu bu ödəyir; modulu testdən testə dəyişməyin iki yolu var, sadəsindən başlayaraq:
1. Mock-un davranışını dəyiş. Modul funksiyalar export edirsə, onları bir dəfə mock et və qaytarılan dəyəri hər testdə təyin et:
import { isEnabled } from "./flags";
vi.mock("./flags", () => ({ isEnabled: vi.fn() }));
it("shows the new editor when the flag is on", () => {
vi.mocked(isEnabled).mockReturnValue(true);
render(<Editor />);
expect(screen.getByRole("heading", { name: "New editor" })).toBeInTheDocument();
});2. Modulu yenidən icra et. Kod asılılığı modul icra olunarkən oxuyursa (editor.ts-in yuxarısında const newEditor = flags.newEditor), mock-u sonradan dəyişməyin heç bir təsiri olmur: dəyər bir dəfə oxunub. Onda yuxarı qaldırılmayan və növbəti dinamik import()-a təsir edən vi.doMock-u modulun yenidən icra olunması üçün vi.resetModules() ilə birlikdə işlət:
beforeEach(() => {
vi.resetModules();
});
it("uses the new editor when the flag is on", async () => {
vi.doMock("./flags", () => ({ newEditor: true }));
const { editorKind } = await import("./editor");
expect(editorKind()).toBe("new");
});
it("keeps the old editor when the flag is off", async () => {
vi.doMock("./flags", () => ({ newEditor: false }));
const { editorKind } = await import("./editor");
expect(editorKind()).toBe("old");
});Faylın yuxarısındakı statik import-lar vi.doMock işləməmişdən əvvəl icra olunub, ona görə test olunan modul ondan sonra dinamik import olunmalıdır. vi.resetModules() modul keşini təmizləyir, mock reyestrini isə yox; qeydiyyatdakı mock-u vi.doUnmock(path) silir.
İkinci yol işləyir, amma test etmək çətin olan dizaynın əlamətidir: konfiqurasiyanı import zamanı oxuyan modul. Flag-i funksiyanın içində oxumaq (birinci yol) və ya onu prop yaxud arqument kimi ötürmək həm testi, həm də kodu sadələşdirir.
Mock-ları dürüst saxla. Hansı üsul olursa olsun, mock modulun yalnız sən onu yazdığın gün nə qaytardığını deyir. importOriginal()-dan başlayan və yalnız yan təsirli hissələri əvəz edən factory-lərə üstünlük ver ki, modulun qalan hissəsi real davranışını saxlasın; tiplərdən də istifadə et (vi.mock(import("./flags"), ...)) ki, real modulun forması dəyişəndə kompilyator bunu görsün.
vi.mock runs once per file, before the imports. That covers most needs; there are two ways to vary a module between tests, from the simpler:
1. Change the mock's behaviour. If the module exports functions, mock them once and set the return value in each test:
import { isEnabled } from "./flags";
vi.mock("./flags", () => ({ isEnabled: vi.fn() }));
it("shows the new editor when the flag is on", () => {
vi.mocked(isEnabled).mockReturnValue(true);
render(<Editor />);
expect(screen.getByRole("heading", { name: "New editor" })).toBeInTheDocument();
});2. Re-evaluate the module. If the code reads the dependency while the module is evaluated (const newEditor = flags.newEditor at the top of editor.ts), changing the mock later has no effect: the value was read once. Then use vi.doMock, which is not hoisted and applies to the next dynamic import(), together with vi.resetModules() so the module is evaluated again:
beforeEach(() => {
vi.resetModules();
});
it("uses the new editor when the flag is on", async () => {
vi.doMock("./flags", () => ({ newEditor: true }));
const { editorKind } = await import("./editor");
expect(editorKind()).toBe("new");
});
it("keeps the old editor when the flag is off", async () => {
vi.doMock("./flags", () => ({ newEditor: false }));
const { editorKind } = await import("./editor");
expect(editorKind()).toBe("old");
});Static imports at the top of the file were evaluated before vi.doMock ran, so the module under test must be imported dynamically after it. vi.resetModules() clears the module cache but not the mocks registry; vi.doUnmock(path) removes a registered mock.
Option 2 works, but it is a sign of a design that is hard to test: a module that reads configuration at import time. Reading the flag inside the function (option 1) or passing it in as a prop or argument makes the test, and the code, simpler.
Keep the mocks honest. Whatever the technique, a mock only says what the module returned on the day you wrote it. Prefer factories that start from importOriginal() and replace only the parts with side effects, so the rest of the module keeps its real behaviour, and use types (vi.mock(import("./flags"), ...)) so the compiler notices when the real module changes shape.
Contract drift: mock-lar API-yə uyğun gəlməyəndə
Mock API davranışının, mock-un yazıldığı gün çıxarılmış surətidir. Backend done-un adını completed-ə dəyişəndə handler-lər hələ də done qaytarır, bütün testlər keçir, production-da isə bütün tapşırıqlar açıq görünür. Buna contract drift (müqavilənin sürüşməsi) deyilir: mock-lar nə qədər real görünürsə, testlər bir o qədər inamlı və bir o qədər yanlış olur.
Onu tutmağın yolları, təxminən ən ucuzundan başlayaraq:
Mock-ları API-nin tipləri ilə tiplə. Client-in tipləri API-nin sxemindən generasiya olunursa (məsələn, backend-in dərc etdiyi OpenAPI sənədindən), adı dəyişmiş sahə fixture-larda tip xətasına çevrilir. MSW handler-ləri generic tipləri Params, RequestBodyType, ResponseBodyType sırası ilə qəbul edir, onda HttpResponse.json() cavab tipinə uyğun olmalıdır:
import type { Task } from "../api/types";
http.patch<{ id: string }, { done: boolean }, Task>(`${API}/tasks/:id`, async ({ params, request }) => {
const { done } = await request.json();
return HttpResponse.json({ id: params.id, title: "Write the release notes", done });
});Fixture-ları tətbiqin sxemindən keçir. Client cavabları sərhəddə yoxlayırsa (), məsələn, Zod sxemi ilə, fixture-ları testdə eyni sxemlə parse et. Real client-in rədd edəcəyi fixture o zaman pozulmuş müqaviləni gizlətmək əvəzinə CI-da sınır.
Fixture-ları bir yerdə qur. makeTask({ done: true }) kimi factory-lər o deməkdir ki, formanın dəyişməsi obyekti kopyalamış qırx handler yox, bir düzəliş tələb edir.
Contract testləri. Martin Fowler contract testini real servis (onun test instansiyası) üzərində işləyən və test double-ın servisi düzgün təmsil etdiyini yoxlayan test kimi təsvir edir; burada datanın dəyərlərindən çox formatı vacibdir. Onlar hər commit-də işləməli deyil; cədvəlləri servisin dəyişikliklərinə uyğunlaşır.
Bir neçə real end-to-end yoxlaması. Ən vacib ssenariləri real backend ilə, mock-suz kimi saxla. Onlar yavaşdır, ona görə sayları azdır, amma pozulmuş müqavilə istifadəçilər görməzdən əvvəl haradasa üzə çıxacaq.
Bir handler dəsti. Unit testlər, Storybook və lokal development (setupWorker vasitəsilə) hərəsi öz saxta API-sini saxlayırsa, sürüşə biləcək üç surət var. Bir handlers modulunu paylaş.
Məqsəd mock etməyi dayandırmaq deyil. Mock-lu sürətli testlər saniyələr içində rəy verir; yuxarıdakı yoxlamalar isə mock-ların production-da işləyən API-ni hələ də təsvir etdiyinə əmin olmaq üçündür.
A mock is a copy of the API's behaviour taken on the day it was written. When the backend renames done to completed, the handlers still answer done, every test passes, and production shows every task as open. This is contract drift: the more realistic the mocks look, the more confident and the more wrong the tests become.
Ways to catch it, roughly from the cheapest:
Type the mocks with the API's types. If the client's types are generated from the API's schema (for example an OpenAPI document the backend publishes), a renamed field becomes a type error in the fixtures. MSW handlers take generic types in the order Params, RequestBodyType, ResponseBodyType, and HttpResponse.json() must then match the response type:
import type { Task } from "../api/types";
http.patch<{ id: string }, { done: boolean }, Task>(`${API}/tasks/:id`, async ({ params, request }) => {
const { done } = await request.json();
return HttpResponse.json({ id: params.id, title: "Write the release notes", done });
});Run fixtures through the app's schema. If the client validates responses at the boundary (), for example with a Zod schema, parse the fixtures with the same schema in a test. A fixture the real client would reject then fails in CI instead of hiding a broken contract.
Build fixtures in one place. Factories like makeTask({ done: true }) mean a shape change is one edit, not forty handlers that each copied the object.
Contract tests. Martin Fowler describes a contract test as one that runs against the real service (a test instance) and checks that a test double is an accurate representation of it, caring more about the format of the data than its values. They do not have to run on every commit; their schedule follows the service's changes.
A few real end-to-end checks. Keep the most important journeys as against a real backend, unmocked. They are slow, so there are few of them, but a broken contract then fails somewhere before users see it.
One set of handlers. If unit tests, Storybook and local development (through setupWorker) each keep their own fake API, there are three copies to drift. Share one handlers module.
The goal is not to stop mocking. Fast tests with mocks give feedback in seconds; the checks above make sure the mocks still describe the API that runs in production.
Müsahibə üçün məsləhətlər
30 saniyəlik cavab. "Mən şəbəkə sərhədində mock edirəm, adətən MSW ilə: handler-lər serverin nə cavab verdiyini təsvir edir, setupServer Node-da sorğuları tutur, real fetch, wrapper və komponent isə hamısı işləyir. Xətaları, boş datanı və yavaş cavabları əhatə etmək üçün handler-i hər testdə server.use() ilə override edirəm, hər testdən sonra handler-ləri sıfırlayıram və heç bir handler-ə uyğun gəlməyən sorğuları xəta ilə dayandırıram. vi.mock-u analitika və ya feature flag-lər kimi şəbəkə olmayan modullar üçün işlədirəm və bilirəm ki, o, yuxarı qaldırılır və modulu hər import edən üçün əvəz edir. Contract drift-ə də diqqət edirəm: tiplənmiş fixture-lar, tətbiqin işlətdiyi eyni sxem və bir neçə mock-suz E2E test."
Gözlənilən suallar
- Niyə
fetch-i və ya öz API modulunu mock etməyək? Hər ikisi testi səhvin ən çox ehtimal olunduğu koddan yuxarıda kəsir və onu kodun çağırış formasına bağlayır. Şəbəkə səviyyəsindəki mock davranışı saxlayan refaktorinqlərdən sağ çıxır. - Xəta vəziyyətini necə test edirsən? 500 və
HttpResponse.error()iləserver.use(); izah et ki, 500-dəfetchok: falseilə resolve olur, şəbəkə xətası isə onu reject edir. vi.mock-un yuxarı qaldırılması nə deməkdir? O, import-lardan əvvəl işləyir; factory faylın dəyişənlərini işlədə bilməz,vi.hoistedilə yaradılanlar istisnadır; iç-içə yazılmışvi.mockVitest 5-də xəta atır; yuxarı qaldırılmayan variantvi.doMock-dur.- Adlı export-a qoyduğum spy niyə çağırışı görmür? Çağıran eyni moduldadır və öz lokal binding-ini işlədir, ya da modul sistemi namespace xassələrini yenidən təyin etməyə icazə vermir.
{ spy: true }iləvi.mockişlət, modulu böl və ya asılılığı inject et. - Mock-ların hələ də backend-ə uyğun olduğunu necə bilirsən? Generasiya olunmuş tiplər, ortaq sxem yoxlaması, contract testləri, bir neçə real E2E yoxlaması.
Bal itirməyə səbəb olan səhvlər
- İstifadəçinin gördüyünü yoxlamaq əvəzinə sorğunun göndərildiyini yoxlamaq.
- Komponentin import etdiyi hər şeyi mock etmək; o zaman test kodu yox, mock-ları yoxlayır.
resetHandlers()və yaunstubAllGlobals()-ı unudub "flaky" nəticəni runner-in boynuna atmaq.onUnhandledFrame-i (MSW 2-dəonUnhandledRequest) default dəyərdə qoymaq; onda səhv URL səssizcə real şəbəkəyə çıxır.
Senior səviyyəni göstərən məqamlar
Qayda yox, kompromisi izah et: konkret asılılıq üçün hansı seam-i seçərdin və niyə, həmin seam-dəki sınma sənə nə deyir və saxta cavabların production-dan uzaqlaşmasının qarşısını necə alırsan. Qeyd et ki, eyni handler-lər testlərə, Storybook-a və lokal development-ə xidmət edə bilər, beləliklə üç yox, bir saxta API saxlanılır.
A 30-second answer. "I mock at the network boundary, usually with MSW: handlers describe what the server answers, setupServer intercepts requests in Node, and the real fetch, wrapper and component all run. I override a handler per test with server.use() to cover errors, empty data and slow responses, reset handlers after each test, and make unhandled requests fail. I use vi.mock for modules that are not the network, like analytics or feature flags, knowing it is hoisted and replaces the module for every importer. And I watch for contract drift: typed fixtures, the same schema the app uses, and a few unmocked E2E tests."
Questions you are likely to get
- Why not mock
fetch, or your own API module? Both cut the test off above the code most likely to be wrong, and both tie it to how the code calls things. A network-level mock survives refactors that keep behaviour. - How do you test an error state?
server.use()with a 500 and withHttpResponse.error(); explain that a 500 resolvesfetchwithok: falsewhile a network error rejects it. - What does it mean that
vi.mockis hoisted? It runs before the imports; the factory cannot use the file's variables except those made withvi.hoisted; a nestedvi.mockthrows in Vitest 5;vi.doMockis the non-hoisted variant. - Why does my spy on a named export not see the call? The caller is in the same module and uses its local binding, or the module system does not allow redefining namespace properties. Use
vi.mockwith{ spy: true }, split the module, or inject the dependency. - How do you know the mocks still match the backend? Generated types, shared schema validation, contract tests, a few real E2E checks.
Mistakes that cost points
- Asserting that a request was sent instead of checking what the user sees.
- Mocking everything a component imports; the test then checks the mocks, not the code.
- Forgetting
resetHandlers()orunstubAllGlobals()and blaming the "flaky" result on the runner. - Leaving
onUnhandledFrame(onUnhandledRequestin MSW 2) at its default, so a wrong URL silently reaches the real network.
Senior signal
Explain the trade-off rather than a rule: which seam you would choose for a given dependency and why, what a failure at that seam tells you, and how you keep the fakes from drifting away from production. Mention that the same handlers can serve tests, Storybook and local development, so one fake API is maintained instead of three.
Mock-ları review edərkən nəyi yoxlamalı
Şəbəkəni və ya modulları mock edən testləri yazmadığın kodda — komanda yoldaşının pull request-ində, kitabxananın nümunəsində, AI assistentin təklifində — review edəndə bu siyahını işlət. Mock-lardakı səhvlər nadir hallarda testi sındırır: real tətbiq sınarkən testlər keçir, ya da dəyişikliklə əlaqəsi olmayan səbəblərdən sınır.
- Şəbəkə şəbəkə sərhədində mock olunubmu? Komandanın öz API wrapper-inin
vi.mock-u və yavi.stubGlobal("fetch")URL qurulmasını, status yoxlamalarını və parse etməni ötürür; MSW handler-lərinə üstünlük ver və test olunan kodun hələ də realfetch-i çağırdığını yoxla. - Heç bir handler-ə uyğun gəlməyən sorğular xəta verirmi?
listen()çağırışındaonUnhandledFrame: "error"-u (MSW 2-dəonUnhandledRequest) axtar; default"warn"ilə səhv URL real şəbəkəyə çıxır və test ondan asılı olur. - Hər override testdən sonra sıfırlanırmı?
afterEach-dəserver.resetHandlers(),vi.unstubAllGlobals()və yaunstubGlobals: true, spy və implementasiyalar üçünrestoreMocksvə yamockReset. Faylı bir testdə.onlyilə və onsuz işə sal: fərqli nəticələr sızan state deməkdir. - Xəta və loading vəziyyətləri düzgün uğursuzluqla test olunurmu? 500-ə
response.ok-un emalı, şəbəkə xətasına (HttpResponse.error())catchlazımdır; hər birinə bir test, üstəgəl boş cavab kodun onları emal edib-etmədiyini göstərir. - Test istifadəçinin gördüyünü yoxlayırmı?
expect(fetch).toHaveBeenCalledWith(...)və ya handler-in çağırıldığını yoxlamaq nəticəni yox, çağırışı test edir; request body-ni handler-də yoxla, assertion-larla isə ekranı yoxla. - Modul mock-u həqiqətən işlədiləcəkmi?
vi.mocküst səviyyədə olmalıdır, factory-də isəvi.hoistedilə yaradılanlardan başqa xarici dəyişən olmamalıdır; export-a qoyulan spy eyni modulun içindəki çağırışları görmür. - Fixture-lar real API-yə uyğundurmu? Onlar API-nin tipləri ilə tiplənməli və ya tətbiqin sxemi ilə parse olunmalı, ortaq factory-lərlə qurulmalı və ssenarinin ən azı bir mock-suz E2E testi ilə dəstəklənməlidir.
Use this list when you review tests that mock the network or modules in code you did not write: a teammate's pull request, a library's example, an AI assistant's suggestion. Mistakes in mocks rarely fail a test; they make tests pass while the real app breaks, or make them fail for reasons unrelated to the change.
- Is the network mocked at the network boundary? A
vi.mockof the team's own API wrapper or avi.stubGlobal("fetch")skips URL building, status checks and parsing; prefer MSW handlers, and check that the code under test still calls the realfetch. - Do unhandled requests fail? Look for
onUnhandledFrame: "error"(onUnhandledRequestin MSW 2) in thelisten()call; with the default"warn", a wrong URL passes through to the real network and the test depends on it. - Is every override reset after the test?
server.resetHandlers()inafterEach,vi.unstubAllGlobals()orunstubGlobals: true, andrestoreMocksormockResetfor spies and implementations. Run the file with and without.onlyon one test: different results mean leaked state. - Are error and loading states tested, and with the right failure? A 500 needs
response.okhandling, a network error (HttpResponse.error()) acatch; one test of each, plus an empty response, shows whether the code handles them. - Does the test assert on what the user sees?
expect(fetch).toHaveBeenCalledWith(...)or a check that a handler was hit tests the call, not the result; validate request bodies in the handler and assert on the screen instead. - Will the module mock actually be used?
vi.mockmust be at the top level, with no outer variables in the factory exceptvi.hoistedones; a spy on an export does not see calls made inside the same module. - Do the fixtures match the real API? They should be typed with the API's types or parsed with the app's schema, built by shared factories, and backed by at least one unmocked E2E test of the journey.