End-to-end tests with Playwright
What an end-to-end test proves and what it costs, and how to write Playwright tests that stay reliable: user-facing locators, auto-waiting and web-first assertions, isolated contexts and fixtures, signing in once with storageState, page.route, projects and CI, and debugging with traces.
Reading level
Shows sections up to the selected level.
Before you start
This topic starts at Junior level.
What an end-to-end test proves
real tətbiqi real brauzerdə istifadəçi kimi idarə edir: URL açır, klikləyir, yazır və ekranda nə göründüyünü yoxlayır. Test ilə nəticə arasında istifadəçinin asılı olduğu hər şey dayanır: production build-i, router, CSS, brauzerin özü, cookie-lər və yönləndirmələr, API və onun arxasındakı verilənlər bazası.
E2E testləri dəyərli edən məhz budur. Onlar jsdom-da işləyən unit və görə bilmədiyi problemləri tutur:
- sticky banerin örtdüyü və ya CSS-in gizlətdiyi düymə, ona görə klik ona heç vaxt çatmır;
- sınmış route, çatışmayan mühit dəyişəni, chunk-lardan birini daxil etməyən build;
- sahə adı fərqləndiyi üçün backend-in sorğusunu rədd etdiyi form;
SameSitevə yaSecureatributuna görə brauzerin göndərmədiyi sessiya cookie-si;- Chromium-da işləyən, Safari-nin arxasındakı engine olan WebKit-də isə sınan funksionallıq.
Onları baha edən də budur:
- Yavaşdır. Brauzer açılır, tətbiq yüklənir, real sorğular gedib-gəlir. Bir test millisaniyələr yox, saniyələr çəkir, yüzlərlə testdən ibarət dəst isə paralel işləsə belə dəqiqələr çəkir.
- Hərəkət edən hissələr çoxdur. Bazadakı data, şəbəkə vaxtları, animasiyalar və üçüncü tərəf skriptləri testi dəyişikliklə əlaqəsi olmayan səbəblərdən sındıra bilər. çoxu buradan gəlir.
- Uğursuzluqlar qeyri-müəyyəndir. "Checkout testi sındı" UI-da, API-də, datada və ya testin özündə bug demək ola bilər.
- Hazırlıq. Tətbiq lokal və CI-da backend və test datası ilə işləməlidir.
Ona görə E2E testlər hər halı yox, istifadəçi ssenarilərini əhatə edir: daxil olmaq, istifadəçilərin gəldiyi əsas axınlar (yaratmaq, redaktə etmək, ödəmək, dərc etmək) və bir neçə sistemdən keçən yollar. Hər ssenariyə bir test hissələrin bir-birinə düzgün bağlandığını sübut edir. Validasiya, formatlama və xəta kodlarının kənar halları daha sürətli testlərə aiddir. Martin Fowler-in təsvir etdiyi test piramidası və Kent C. Dodds-un testing trophy-si orta qatlar barədə razılaşmır, amma hər ikisi E2E testləri zirvəyə qoyur: onlar azdır və hər biri bahadır.
E2E test nadir hallarda və real səbəbdən sınanda ən dəyərlidir. Bu mövzunun qalan hissəsi buna necə çatmaq barədədir: istifadəçinin gördüyünü tapan locator-lar, təxmin etməyən gözləmə və bir-birinə sızmayan testlər.
An drives the real app in a real browser, the way a user does: it opens a URL, clicks, types and checks what appears. Between the test and the result sits everything a user depends on: the production build, the router, the CSS, the browser itself, cookies and redirects, the API and the database behind it.
That is what makes E2E tests valuable. They catch problems that unit tests and in jsdom cannot see:
- a button covered by a sticky banner or hidden by CSS, so a click never reaches it;
- a broken route, a missing environment variable, a build that leaves out a chunk;
- a form whose request the backend rejects because a field name differs;
- a session cookie the browser does not send because of its
SameSiteorSecureattribute; - a feature that works in Chromium and breaks in WebKit, the engine behind Safari.
And it is what makes them expensive:
- Slow. A browser starts, the app loads, real requests travel. A test takes seconds, not milliseconds, and a suite of hundreds takes minutes even in parallel.
- More moving parts. Data in the database, network timing, animations and third-party scripts can all fail a test for reasons unrelated to the change. This is where most come from.
- Vague failures. "The checkout test failed" can mean a bug in the UI, the API, the data or the test.
- Setup. The app must run with a backend and test data, locally and in CI.
So E2E tests cover user journeys, not every case: signing in, the main flows that users come for (create, edit, pay, publish) and the paths that cross several systems. One test per journey proves that the parts are wired together. The edge cases of validation, formatting and error codes belong in faster tests. The test pyramid, which Martin Fowler describes, and Kent C. Dodds' testing trophy disagree about the middle layers, but both put E2E tests at the top: few of them, each one expensive.
An E2E test is worth the most when it fails rarely and for a real reason. The rest of this topic is about getting there: locators that find what users see, waiting that does not guess, and tests that cannot leak into each other.
A first test with Playwright Test
npm init playwright@latestKomanda @playwright/test-i, playwright.config.ts-i, nümunə testi və istəsən, GitHub Actions workflow-unu əlavə edir. npx playwright test testləri işə salır, default olaraq headless və Chromium, Firefox və WebKit-də paralel; npx playwright show-report HTML hesabatını açır.
// tests/tasks.spec.ts
import { test, expect } from "@playwright/test";
test("adds a task", async ({ page }) => {
await page.goto("/tasks");
await page.getByLabel("New task").fill("Write the release notes");
await page.getByRole("button", { name: "Add task" }).click();
await expect(page.getByRole("listitem").filter({ hasText: "Write the release notes" })).toBeVisible();
await expect(page.getByRole("status")).toHaveText("1 task left");
});pagefixture-dir: Playwright-in bu test üçün yaratdığı təzə səhifə.- Config-də
use.baseURLtəyin olunanda (məsələn,"http://localhost:3000")page.goto("/tasks")path qəbul edir;webServerseçimi isə testlərdən əvvəl tətbiqi işə sala bilər. - Locator-lar elementi istifadəçinin tapacağı kimi tapmağı təsvir edir. Playwright
getByRole-u (rol və üzrə), form sahələri üçüngetByLabel-i,getByText,getByPlaceholder,getByAltText,getByTitle-ı, istifadəçiyə görünən heç nə uyğun gəlməyəndə isəgetByTestId-ni (data-testidatributu) tövsiyə edir. getByRole("button", { name: "Add task" })adı default olaraq böyük-kiçik hərfə həssas olmayan alt sətir kimi uyğunlaşdırır;exact: truetam və hərfə həssas uyğunluq tələb edir.- Locator-lar tənbəldir: action və ya assertion onu işlədənə qədər heç nə axtarılmır, hər istifadədə isə element yenidən tapılır, ona görə arada baş verən yenidən render zərər vermir.
- Locator-lar sərtdir (strict): birdən çox elementə uyğun gələn locator üzərində action xəta atır.
first()-ə əl atmaq əvəzinə onufilter({ hasText })ilə və ya zəncirləməklə daralt (row.getByRole("button", { name: "Delete" })). - Action-lar locator-un metodlarıdır:
click(),fill(),check(),selectOption(),press(),hover(),setInputFiles().
Niyə CSS selector-lar yox, rollar və label-lər: class-lar və DOM strukturu hər redizaynda dəyişir, rollar, adlar və label-lər isə yalnız istifadəçinin gördüyü UI dəyişəndə dəyişir. Kontrolun accessible name-i olmayanda rol sorğusu da sınır, bu isə real bug-dır. npx playwright codegen <url> kliklərini rol, mətn və test id locator-ları ilə test koduna yazır; onun nəticəsinə qaralama kimi bax.
npm init playwright@latestThe command adds @playwright/test, a playwright.config.ts, an example test and, if you choose, a GitHub Actions workflow. npx playwright test runs the tests, by default headless and in parallel in Chromium, Firefox and WebKit; npx playwright show-report opens the HTML report.
// tests/tasks.spec.ts
import { test, expect } from "@playwright/test";
test("adds a task", async ({ page }) => {
await page.goto("/tasks");
await page.getByLabel("New task").fill("Write the release notes");
await page.getByRole("button", { name: "Add task" }).click();
await expect(page.getByRole("listitem").filter({ hasText: "Write the release notes" })).toBeVisible();
await expect(page.getByRole("status")).toHaveText("1 task left");
});pageis a fixture: a fresh page that Playwright creates for this test.page.goto("/tasks")takes a path whenuse.baseURLis set in the config (for example"http://localhost:3000"); thewebServeroption can start the app before the tests.- Locators describe how to find an element the way a user would. Playwright recommends
getByRole(by role and ),getByLabelfor form fields,getByText,getByPlaceholder,getByAltText,getByTitle, andgetByTestId(thedata-testidattribute) when nothing user-facing fits. getByRole("button", { name: "Add task" })matches the name as a case-insensitive substring by default;exact: trueasks for a whole, case-sensitive match.- Locators are lazy: nothing is looked up until an action or assertion uses them, and every use finds the element again, so a re-render in between does no harm.
- Locators are strict: an action on a locator that matches more than one element throws. Narrow it with
filter({ hasText })or by chaining (row.getByRole("button", { name: "Delete" })) instead of reaching forfirst(). - Actions are methods on the locator:
click(),fill(),check(),selectOption(),press(),hover(),setInputFiles().
Why roles and labels rather than CSS selectors: classes and DOM structure change with every redesign, while roles, names and labels change only when the UI the user sees changes. A role query also fails when a control has no accessible name, which is a real bug. npx playwright codegen <url> records your clicks as test code with role, text and test id locators; treat its output as a draft.
Auto-waiting and web-first assertions
Səhifələr asinxron dəyişir: sorğu bitir, komponent render olunur, animasiya sona çatır. Playwright sabit müddət yox, düzgün şərt gözləyir.
Action-lardan əvvəl . click()-dən əvvəl Playwright locator-un dəqiq bir elementə uyğun gəldiyini və həmin elementin:
- görünən olduğunu: boş olmayan bounding box-u var və
visibility: hiddenyoxdur; - stabil olduğunu: ən azı ardıcıl iki animasiya kadrı ərzində eyni bounding box, yəni animasiyanın ortasında deyil;
- event-ləri qəbul etdiyini: klikin həqiqətən dəyəcəyi elementdir, overlay-in altındakı nəsə deyil;
- aktiv olduğunu: disabled deyil
yoxlayır. fill() daha az şey yoxlayır: görünən, aktiv və redaktə oluna bilən (read-only olmayan). Yoxlamalar vaxtında keçməsə, action TimeoutError ilə uğursuz olur. force: true seçimi vacib olmayan yoxlamaları ötürür; onu nadir hallarda işlət, çünki real istifadəçini dayandıracaq overlay-in içindən klikləyə bilər.
Web-first assertion-lar. await expect(locator).toBeVisible() bir dəfə yoxlamır: şərt ödənənə və ya expect timeout-u, default olaraq 5 saniyə, bitənə qədər təkrar yoxlayır. toHaveText, toContainText, toHaveValue, toHaveCount, toBeChecked, toHaveURL, toHaveTitle və digər locator və səhifə assertion-ları da belədir.
// Mesaj görünənə və ya 5 saniyə keçənə qədər təkrar yoxlayır
await expect(page.getByRole("status")).toHaveText("Task saved");
// Bir dəfə, elə indi yoxlayır: flaky
expect(await page.getByRole("status").isVisible()).toBe(true);İkinci sətir vəziyyəti bir anda oxuyur və heç vaxt təkrar yoxlamayan adi boolean-ı müqayisə edir. Playwright-in best practices səhifəsi məhz bu sətri yazılmamalı nümunə kimi göstərir.
Sabit gözləmələr pis əlamətdir. await page.waitForTimeout(2000) yavaş CI maşınında azdır, başqa hər yerdə isə boş itən vaxtdır. Playwright-in API sənədləri onun yalnız debug üçün işlədilməli olduğunu deyir, çünki vaxt gözləyən testlər mahiyyətcə flaky-dir. Əvəzinə mənalı bir şey gözlə: element, mətn, URL (await expect(page).toHaveURL(/\/tasks\/\d+/)) və ya cavab.
Hər Playwright çağırışını await et. Unudulmuş await testin action və ya assertion işləməmiş bitməsinə imkan verir, ona görə test heç nəyi yoxlamadan keçə bilər. Playwright-in best practices səhifəsi bunu tutmaq üçün @typescript-eslint/no-floating-promises lint qaydasını tövsiyə edir.
Bilməli olduğun timeout-lar: testə default olaraq 30 saniyə, assertion-a 5 saniyə verilir, action-ın isə öz timeout-u yoxdur, ona görə onu testin timeout-u məhdudlaşdırır.
Pages change asynchronously: a request finishes, a component renders, an animation ends. Playwright waits for the right condition instead of a fixed time.
before actions. Before click(), Playwright checks that the locator resolves to exactly one element and that the element is:
- visible: it has a non-empty bounding box and no
visibility: hidden; - stable: the same bounding box for at least two consecutive animation frames, so not mid-animation;
- receiving events: it is the element the click would really hit, not something under an overlay;
- enabled: not disabled.
fill() checks fewer things: visible, enabled and editable (not read-only). If the checks do not pass in time, the action fails with a TimeoutError. The force: true option skips the non-essential checks; use it rarely, because it can click through an overlay that would stop a real user.
Web-first assertions. await expect(locator).toBeVisible() does not check once: it retries until the condition holds or the expect timeout runs out, 5 seconds by default. The same is true of toHaveText, toContainText, toHaveValue, toHaveCount, toBeChecked, toHaveURL, toHaveTitle and the other locator and page assertions.
// Retries until the message appears, or 5 seconds pass
await expect(page.getByRole("status")).toHaveText("Task saved");
// Checks once, right now: flaky
expect(await page.getByRole("status").isVisible()).toBe(true);The second line reads the state at one moment and compares a plain boolean, which never retries. Playwright's best practices show exactly this line as the one not to write.
Fixed waits are a smell. await page.waitForTimeout(2000) is too short on a slow CI machine and wasted time everywhere else. Playwright's API docs say it should only be used for debugging, because tests that wait for time are inherently flaky. Wait for something meaningful instead: an element, a text, a URL (await expect(page).toHaveURL(/\/tasks\/\d+/)) or a response.
Await every Playwright call. A forgotten await lets the test finish before the action or assertion runs, so it can pass without checking anything. Playwright's best practices recommend the @typescript-eslint/no-floating-promises lint rule to catch it.
The timeouts to know: a test has 30 seconds by default, an assertion 5 seconds, and an action has no timeout of its own, so it is limited by the test's.
Test isolation, browser contexts and fixtures
Hər test yeni browser context alır; Playwright onu öz cookie-ləri və storage-i olan tamamilə yeni brauzer profilinə bənzədir. Resurslara qənaət üçün brauzer prosesi ortaqdır, context isə yox. Ona görə testlər bir-birinin sessiyalarını görmür və istənilən sırada, paralel işləyə bilir. Test faylları ayrı worker proseslərində paralel işləyir (default olaraq məntiqi CPU nüvələrinin yarısı qədər); fullyParallel aktiv deyilsə, bir faylın içindəki testlər ardıcıl işləyir. Worker-lər bir-biri ilə əlaqə saxlaya bilmir.
Context backend-i yox, brauzeri təcrid edir. İki test eyni bazada eyni qeydi redaktə edirsə, context-lərin sayından asılı olmayaraq bir-birinə mane olur. Hər test ehtiyac duyduğu datanı unikal adlarla özü yaratmalı və başqa testin qoyub getdiyi heç nəyə arxalanmamalıdır.
Fixture-lar testə lazım olanı verir. Daxili olanlar page, context (səhifənin təcrid olunmuş context-i), browser (ortaq), browserName və HTTP çağırışları üçün təcrid olunmuş API client-i olan request-dir. test.extend ilə yaratdığın fixture-lar setup və teardown-u bir yerdə saxlayır, yalnız onları istəyən testlər üçün işləyir və başqa fixture-lardan asılı ola bilir:
// tests/fixtures.ts
import { test as base, expect } from "@playwright/test";
type Project = { id: string; name: string };
export const test = base.extend<{ project: Project }>({
project: async ({ request }, use) => {
// Setup: datanı UI ilə yox, API ilə yarat
const response = await request.post("/api/projects", {
data: { name: `Release ${crypto.randomUUID()}` },
});
expect(response.ok()).toBe(true);
const project = (await response.json()) as Project;
await use(project);
// Teardown: test bitəndən sonra, uğursuz olsa belə işləyir
await request.delete(`/api/projects/${project.id}`);
},
});
export { expect };// tests/project.spec.ts
import { test, expect } from "./fixtures";
test("renames a project", async ({ page, project }) => {
await page.goto(`/projects/${project.id}`);
await page.getByRole("button", { name: "Rename" }).click();
await page.getByLabel("Project name").fill("Q4 launch");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Q4 launch");
});await use(...)-dan əvvəlki kod setup-dır, sonrakı isə teardown. request fixture-u da page.goto kimi path-ları baseURL-ə görə resolve edir. Datanı API ilə yaratmaq onlarla klik əvəzinə millisaniyələr çəkir, layihə yaradan ekranın isə öz testi olur.
Every test gets a new browser context, which Playwright compares to a brand-new browser profile, with its own cookies and storage. The browser process is shared to save resources; the context is not. So tests do not see each other's sessions and can run in any order and in parallel. Test files run in parallel in separate worker processes (by default, half the logical CPU cores); the tests inside one file run in order unless fullyParallel is on. Workers cannot talk to each other.
A context isolates the browser, not your backend. If two tests edit the same record in the same database, they interfere however many contexts there are. Each test should create the data it needs, with unique names, and assume nothing that another test left behind.
Fixtures give a test what it needs. The built-in ones are page, context (the page's isolated context), browser (shared), browserName and request, an isolated API client for HTTP calls. Your own fixtures, made with test.extend, keep setup and teardown together, run only for the tests that ask for them, and can depend on other fixtures:
// tests/fixtures.ts
import { test as base, expect } from "@playwright/test";
type Project = { id: string; name: string };
export const test = base.extend<{ project: Project }>({
project: async ({ request }, use) => {
// Setup: create the data through the API, not the UI
const response = await request.post("/api/projects", {
data: { name: `Release ${crypto.randomUUID()}` },
});
expect(response.ok()).toBe(true);
const project = (await response.json()) as Project;
await use(project);
// Teardown: runs after the test, even when it failed
await request.delete(`/api/projects/${project.id}`);
},
});
export { expect };// tests/project.spec.ts
import { test, expect } from "./fixtures";
test("renames a project", async ({ page, project }) => {
await page.goto(`/projects/${project.id}`);
await page.getByRole("button", { name: "Rename" }).click();
await page.getByLabel("Project name").fill("Q4 launch");
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Q4 launch");
});Code before await use(...) is the setup, code after it the teardown. The request fixture resolves paths against baseURL, like page.goto. Creating data through the API takes milliseconds instead of a dozen clicks, and the screen that creates projects gets its own test.
Signing in once with storageState
Hər testdə form vasitəsilə daxil olmaq yavaşdır və login formunu bütün test dəsti üçün tək sınma nöqtəsinə çevirir. Playwright-in tövsiyə etdiyi yanaşma setup project-də bir dəfə daxil olmaq, brauzerin vəziyyətini fayla saxlamaq və hər testi ondan başlatmaqdır:
// tests/auth.setup.ts
import path from "node:path";
import { test as setup, expect } from "@playwright/test";
const authFile = path.join(__dirname, "../playwright/.auth/user.json");
setup("sign in", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Email").fill(process.env.E2E_EMAIL!);
await page.getByLabel("Password").fill(process.env.E2E_PASSWORD!);
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page).toHaveURL("/tasks");
await expect(page.getByRole("button", { name: "Account" })).toBeVisible();
await page.context().storageState({ path: authFile });
});// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
use: { baseURL: "http://localhost:3000" },
projects: [
{ name: "setup", testMatch: /.*\.setup\.ts/ },
{
name: "chromium",
use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" },
dependencies: ["setup"],
},
],
});chromiumondan asılı olduğu üçün setup project birinci işləyir. Sonra hər test saxlanmış vəziyyətdən yaradılan yeni context alır, ona görə daxil olmuş halda başlayır və yenə təcrid olunmuş qalır.storageState()cookie-ləri və local storage-i,indexedDB: trueötürəndə isə IndexedDB-ni də saxlayır. Session storage saxlanmır; Playwright-də onu saxlamaq üçün API yoxdur.- Faylda test hesabının adından iş görmək üçün istifadə oluna biləcək real sessiya cookie-ləri var:
playwright/.auth-u.gitignore-a əlavə et, sessiyanın vaxtı bitəndə isə faylı sil. - Daxil olmamış istifadəçi təcrübəsinin testləri öz faylı üçün vəziyyəti sıfırlayır:
test.use({ storageState: { cookies: [], origins: [] } }). - Bir neçə rol: setup project-də hər rol üçün bir dəfə daxil ol (
admin.json,user.json) və fayl üzrətest.use({ storageState: ... })ilə seç. Eyni anda iki istifadəçiyə ehtiyacı olan test, məsələn, admin-in istifadəçinin göndərdiyini təsdiqləməsi,browser.newContext({ storageState })ilə iki context yaradır. - Hər worker-ə bir hesab. Testlər başqalarının oxuduğu server tərəfi state-i dəyişmirsə, ortaq hesab yaxşıdır. Dəyişirsə, Playwright hər worker üçün ayrıca hesabla daxil olan və
test.info().parallelIndexilə açarlanan worker-scoped fixture tövsiyə edir.
Tətbiq API sorğusu ilə daxil olmağa imkan verirsə, setup formun əvəzinə request işlədə bilər; o zaman login formunun özünə ayrıca adi bir test yazılır.
Signing in through the form in every test is slow, and it makes the login form a single point of failure for the whole suite. Playwright's recommended approach is to sign in once in a setup project, save the browser's state to a file and start every test from it:
// tests/auth.setup.ts
import path from "node:path";
import { test as setup, expect } from "@playwright/test";
const authFile = path.join(__dirname, "../playwright/.auth/user.json");
setup("sign in", async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Email").fill(process.env.E2E_EMAIL!);
await page.getByLabel("Password").fill(process.env.E2E_PASSWORD!);
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page).toHaveURL("/tasks");
await expect(page.getByRole("button", { name: "Account" })).toBeVisible();
await page.context().storageState({ path: authFile });
});// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
use: { baseURL: "http://localhost:3000" },
projects: [
{ name: "setup", testMatch: /.*\.setup\.ts/ },
{
name: "chromium",
use: { ...devices["Desktop Chrome"], storageState: "playwright/.auth/user.json" },
dependencies: ["setup"],
},
],
});- The setup project runs first because
chromiumdepends on it. Every test then gets a new context created from the saved state, so it starts signed in and still isolated. storageState()saves cookies and local storage, and IndexedDB when you passindexedDB: true. Session storage is not saved; Playwright has no API to persist it.- The file holds real session cookies that could be used to act as the test account: add
playwright/.authto.gitignore, and delete the file when the session expires. - Tests of the signed-out experience reset the state for their file:
test.use({ storageState: { cookies: [], origins: [] } }). - Several roles: sign in once per role in the setup project (
admin.json,user.json) and choose per file withtest.use({ storageState: ... }). A test that needs two users at once, such as an admin approving what a user submitted, creates two contexts withbrowser.newContext({ storageState }). - One account per worker. A shared account is fine while tests do not change server-side state that others read. When they do, Playwright recommends a worker-scoped fixture that signs in a separate account for each worker, keyed by
test.info().parallelIndex.
If the app can sign in with an API request, the setup can use request instead of the form; the login form then gets one ordinary test of its own.
Mocking the network with page.route, or not
E2E test real inteqrasiyanı yoxlamaq üçündür, ona görə default olaraq öz backend-ini mock etmə: API-ni saxtalaşdıran test daha yavaş komponent testidir və istənilən mock kimi real API-dən uzaqlaşa bilər. Playwright-in best practices səhifəsi sərhədi sənin idarə etmədiyin şeydə çəkir: üçüncü tərəf asılılıqlarını test etmə və onların cavablarını page.route ilə mock et. Bu hallarda mock et:
- asılılıq başqasınındır: ödəniş provayderi, xəritələr, chat və ya analitika skripti; onun dayanması sənin test dəstini sındırmamalıdır;
- vəziyyəti real backend ilə yaratmaq çətindir: 503, qırılmış bağlantı, yavaş cavab.
test("shows a banner when the tasks API fails", async ({ page }) => {
await page.route("**/api/tasks", (route) =>
route.fulfill({ status: 503, json: { message: "Maintenance" } }),
);
await page.goto("/tasks");
await expect(page.getByRole("alert")).toHaveText("Tasks are unavailable. Try again later.");
});Route-u page.goto()-dan əvvəl qeydiyyata al; ondan əvvəl göndərilən sorğular tutulmur. Handler nə edə bilər:
route.fulfill({ status, json, headers, body })şəbəkəsiz cavab verir;jsoncontent type-ı da təyin edir, status isə default olaraq 200-dür;route.abort(errorCode)sorğunu şəbəkə xətası kimi uğursuz edir (default"failed", ya da"timedout"və"internetdisconnected"kimi kodlar);route.continue()sorğunu şəbəkəyə göndərir, istəsən header-ləri, metodu və ya URL-i dəyişərək;route.fetch()real sorğunu icra edir, ona görə real cavabı dəyişibroute.fulfill({ response, json })ilə ötürə bilərsən.
Bir neçə route uyğun gələndə sonuncu qeydiyyata alınan birinci işləyir. route.fallback() sorğunu növbəti uyğun route-a ötürür, route.continue() isə qalanlarını ötürüb onu birbaşa şəbəkəyə göndərir. Səhifə route-ları context route-larından üstündür, { times: 1 } isə route-un bir dəfə işləməsini təmin edir. Qeydə alınmış cavabların bütöv dəsti üçün page.routeFromHAR() HAR faylını təkrar oynadır.
API sənədlərindən iki xəbərdarlıq. Routing-i aktiv etmək HTTP keşini söndürür, ona görə keşləmə davranışının testi həmin sorğuları route etməməlidir. Və page.route Service Worker-in tutduğu sorğuları görmür; interception-a güvənəndə Playwright use-da serviceWorkers: "block" tövsiyə edir. Bu, tətbiq öz Service Worker-ini qeydiyyata alanda və ya test olunan build-də MSW-ninki kimi mock worker-i aktiv qalanda vacibdir.
Tətbiqin API-sinin çoxunu route etdiyini görürsənsə, test artıq end-to-end deyil. Həmin halı şəbəkə mock-ları olan komponent testinə köçür, E2E testi isə real backend-də saxla.
An E2E test exists to check the real integration, so by default do not mock your own backend: a test that fakes your API is a slower component test, and it can drift from the real API like any mock. Playwright's best practices draw the line at what you do not control: avoid testing third-party dependencies and mock their responses with page.route. Mock when:
- the dependency belongs to someone else: a payment provider, maps, a chat or analytics script; its outage should not fail your suite;
- the state is hard to produce with the real backend: a 503, a dropped connection, a slow response.
test("shows a banner when the tasks API fails", async ({ page }) => {
await page.route("**/api/tasks", (route) =>
route.fulfill({ status: 503, json: { message: "Maintenance" } }),
);
await page.goto("/tasks");
await expect(page.getByRole("alert")).toHaveText("Tasks are unavailable. Try again later.");
});Register the route before page.goto(); requests sent earlier are not intercepted. What a handler can do:
route.fulfill({ status, json, headers, body })answers without the network;jsonalso sets the content type, and the status defaults to 200;route.abort(errorCode)fails the request like a network error ("failed"by default, or codes such as"timedout"and"internetdisconnected");route.continue()sends the request to the network, optionally with changed headers, method or URL;route.fetch()performs the real request, so you can change the real response and pass it on withroute.fulfill({ response, json }).
When several routes match, the one registered last runs first. route.fallback() hands the request to the next matching route, while route.continue() sends it straight to the network and skips the rest. Page routes take precedence over context routes, and { times: 1 } makes a route apply once. For a whole set of recorded responses, page.routeFromHAR() replays a HAR file.
Two caveats from the API docs. Enabling routing disables the HTTP cache, so a test of caching behaviour must not route those requests. And page.route does not see requests that a Service Worker intercepts; Playwright recommends serviceWorkers: "block" in use when you rely on interception. That matters if the app registers its own Service Worker, or if a mocking worker such as MSW's was left enabled in the build under test.
If you find yourself routing most of the app's API, the test has stopped being end-to-end. Move that case into a component test with network mocks and keep the E2E test on the real backend.
Projects, parallelism and CI
Project-lər eyni testləri fərqli parametrlərlə işə salır: brauzerlər, emulyasiya olunan cihazlar və ya əvvəlcə setup addımı. Playwright sənədlərinin göstərdiyi CI parametrləri ilə tipik config:
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "tests",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI ? "blob" : "html",
use: {
baseURL: "http://localhost:3000",
trace: "on-first-retry",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
{ name: "mobile-safari", use: { ...devices["iPhone 12"] } },
],
webServer: {
command: "npm run start",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
},
});npx playwright test --project=webkit bir project-i işə salır. Cihaz qeydi həmin cihazın brauzerini, viewport-unu və user agent-ini təyin edir; bu, real telefon yox, emulyasiyadır.
forbidOnlytəsadüfən commit olunmuştest.onlyolanda run-ı uğursuz edir.retries: default olaraq uğursuz testlər təkrarlanmır. Retry-larla əvvəlcə sınan, sonra keçən test uğurlu (passed) kimi yox, flaky kimi göstərilir, uğursuzluq isə worker prosesini və onun brauzerini atıb yenisini başladır. "Flaky"-ni bug hesabatı kimi oxu: retry-lar pipeline-ı hərəkətdə saxlayır, heç nəyi düzəltmir.- CI-da
workers: 1: Playwright-in CI bələdçisi stabillik və təkrarlana bilənliyə üstünlük vermək üçün bunu tövsiyə edir. Güclü CI maşınları olan komandalar daha çox worker işlədir. - Sharding test dəstini maşınlar arasında bölür:
npx playwright test --shard=1/4-dən--shard=4/4-ə qədər, hər biri öz CI job-unda.fullyParallel: trueilə testlər tək-tək, onsuz isə bütöv fayllar paylanır. Hər shardblobhesabatı yazır,npx playwright merge-reports --reporter html ./all-blob-reportsisə onları bir HTML hesabatına çevirir. webServertestlərdən əvvəl tətbiqi işə salır;reuseExistingServer: !process.env.CIlokalda işləyən serverini təkrar istifadə edir, CI-da isə həmişə yenisini başladır.- CI job-unda brauzerləri
npx playwright install --with-depsilə (və ya yalnız test etdiklərini,npx playwright install chromium --with-deps) quraşdır vəplaywright-report/-u artifact kimi yüklə ki, hesabat və onun trace-ləri job-dan sonra da qalsın.
Hər pull request-də hansı brauzerlərin işləyəcəyi xərc qərarıdır: çox vaxt hər pull request-də biri, tam matris isə gecə. WebKit-i harasa daxil et: o, Safari-nin engine-idir və hamı Chromium-da işləyəndə onun bug-larını gözdən qaçırmaq asandır.
Projects run the same tests with different settings: browsers, emulated devices, or a setup step first. A typical config, with the CI settings Playwright's docs show:
// playwright.config.ts
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
testDir: "tests",
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI ? "blob" : "html",
use: {
baseURL: "http://localhost:3000",
trace: "on-first-retry",
},
projects: [
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
{ name: "mobile-safari", use: { ...devices["iPhone 12"] } },
],
webServer: {
command: "npm run start",
url: "http://localhost:3000",
reuseExistingServer: !process.env.CI,
},
});npx playwright test --project=webkit runs one project. A device entry sets the browser, viewport and user agent of that device; it is emulation, not a real phone.
forbidOnlyfails the run if atest.onlywas committed by accident.retries: failing tests are not retried by default. With retries, a test that fails and then passes is reported as flaky, not as passed, and a failure discards the worker process and its browser and starts a fresh one. Read "flaky" as a bug report: retries keep the pipeline moving, they do not fix anything.workers: 1on CI: Playwright's CI guide recommends it to prioritize stability and reproducibility. Teams with powerful CI machines run more workers.- Sharding spreads the suite across machines:
npx playwright test --shard=1/4up to--shard=4/4, each in its own CI job. WithfullyParallel: truetests are distributed one by one; without it, whole files. Each shard writes ablobreport, andnpx playwright merge-reports --reporter html ./all-blob-reportsturns them into one HTML report. webServerstarts the app before the tests;reuseExistingServer: !process.env.CIreuses your running server locally and always starts a fresh one on CI.- In the CI job, install the browsers with
npx playwright install --with-deps(or only the ones you test,npx playwright install chromium --with-deps) and uploadplaywright-report/as an artifact, so the report and its traces outlive the job.
Which browsers run on every pull request is a cost decision: often one on each pull request and the full matrix nightly. Include WebKit somewhere: it is Safari's engine, and its bugs are easy to miss when everyone develops in Chromium.
Debugging failures: traces, screenshots and UI mode
CI-da qırmızı E2E test adətən "Timed out 5000ms waiting for expect(locator).toBeVisible()" kimi bir şey deyir. Sual elementin niyə heç vaxt görünmədiyidir, cavab isə adətən trace-dədir.
Trace-lər hər action-ı ondan əvvəlki, onun anındakı və ondan sonrakı DOM snapshot-ları ilə, üstəlik şəbəkə sorğuları, konsol mesajları, xətalar və kod sətri ilə qeydə alır. use-dakı trace seçimi:
"on-first-retry": uğursuz test ilk dəfə təkrarlananda qeydə al; Playwright nümunələrindəki parametr, testlər keçdikcə heç nəyə başa gəlmir;"on-all-retries": hər retry-ı qeydə al;"retain-on-failure": hər testi qeydə al, trace-i yalnız uğursuz olanda saxla;"on": hər test; sənədlər bunu performans üçün ağır adlandırır.
HTML hesabatını aç (npx playwright show-report) və trace ikonuna kliklə, ya da npx playwright show-trace path/to/trace.zip işə sal. trace.playwright.dev trace-i brauzerdə açır; faylı lokal yükləyir və heç yerə data göndərmir.
Bu ardıcıllıqla nəyə baxmalı:
- Uğursuz action və onun snapshot-ları. Element orada idimi? Dialoq onu örtmüşdü? Spinner-in arxasında idi? Hələ köhnə mətni göstərirdi?
- Network tab-ı. 500, yavaş API çağırışı və ya heç göndərilməmiş sorğu görünməyən elementlərin çoxunu izah edir.
- Console tab-ı. Render-i dayandırmış JavaScript xətası.
- Locator. Actions tab-ı hər action-ın işlətdiyi locator-u göstərir; başqa şeyə uyğun gəlmiş locator tez-tez rast gəlinən səbəbdir.
screenshot: "only-on-failure" və video: "retain-on-failure" hesabata şəkil əlavə edir, amma Playwright-in best practices səhifəsi CI uğursuzluqları üçün trace viewer-ə üstünlük verir: o, yalnız pikselləri yox, DOM-u, şəbəkəni və kodu göstərir.
Flaky uğursuzluqlara başqa trace lazımdır. "on-first-retry" ilə trace retry-dan gəlir; retry keçibsə, uğurlu run-a baxırsan. Testi "retain-on-failure"-a keçir və trace ilə uğursuz olana qədər dəfələrlə işə sal: lokalda npx playwright test --repeat-each=20 ilə və ya CI-da. Uğursuz trace-i keçənlə müqayisə et: fərq adətən gec gələn cavab, yenidən render olunan element və ya başqa testin dəyişdiyi datadır.
Lokalda:
npx playwright test --uiUI mode-u açır: testləri işə salmaq və filtrləmək, watch mode, hər addımda zamanda səyahət, kursoru snapshot üzərinə gətirməklə locator seçmək, Network və Console panelləri.npx playwright test --debugPlaywright Inspector ilə işləyir, ona görə action-lar arasında addım-addım keçə bilərsən.
A red E2E test on CI usually says something like "Timed out 5000ms waiting for expect(locator).toBeVisible()". The question is why the element never appeared, and the answer is usually in the trace.
Traces record every action with DOM snapshots before, during and after it, plus network requests, console messages, errors and the source line. The trace option in use:
"on-first-retry": record when a failed test is retried for the first time; the setting in Playwright's examples, free while tests pass;"on-all-retries": record every retry;"retain-on-failure": record every test, keep the trace only when it failed;"on": every test, which the docs call performance-heavy.
Open the HTML report (npx playwright show-report) and click the trace icon, or run npx playwright show-trace path/to/trace.zip. trace.playwright.dev opens a trace in the browser; it loads the file locally and sends no data anywhere.
What to look at, in this order:
- The failing action and its snapshots. Was the element there? Covered by a dialog? Behind a spinner? Still showing the old text?
- The Network tab. A 500, a slow API call or a request that never went out explains most missing elements.
- The Console tab. A JavaScript error that stopped rendering.
- The locator. The Actions tab shows the locator each action used; a locator that matched something else is a common cause.
screenshot: "only-on-failure" and video: "retain-on-failure" add pictures to the report, but Playwright's best practices prefer the trace viewer for CI failures: it shows the DOM, the network and the code, not only pixels.
Flaky failures need a different trace. With "on-first-retry", the trace comes from the retry; if the retry passed, you are looking at a passing run. Switch the test to "retain-on-failure" and run it many times, locally with npx playwright test --repeat-each=20 or on CI, until it fails with a trace. Compare the failing trace with a passing one: the difference is usually a response that arrived later, an element that re-rendered, or data another test changed.
Locally:
npx playwright test --uiopens UI mode: run and filter tests, watch mode, time travel through each step, pick a locator by hovering over the snapshot, and the network and console tabs.npx playwright test --debugruns with the Playwright Inspector, so you can step through actions.
Keeping the E2E suite small and trustworthy
E2E test dəsti öz məqsədinə iki yolla çatmır: hər dəyişiklikdə işə salmaq üçün çox yavaşlayır, ya da o qədər flaky olur ki, qırmızı nəticəyə məhəl qoyulmur. Hər ikisi bəxtsizlik yox, dizayn qərarıdır.
Kənarda qalanlar. Hər validasiya mesajı, hər formatlama qaydası, hər API xəta kodu və hər icazə kombinasiyası şəbəkə mock-ları olan komponent testlərinə və ya hər halın millisaniyələrlə işlədiyi unit testlərə aiddir. Formun E2E testi düzgün göndərişin bütün stack-dən keçdiyini və bir yanlış dəyərin xəta göstərdiyini yoxlayır; qalan qaydalar aşağıda test olunur. Üçüncü tərəf servisləri, kitabxanaların daxili işləri və piksel səviyyəsində üslub (ayrıca vizual testlər işlətmirsənsə) da kənarda qalır.
Sənə aid data. Qeydləri paylaşan testlər paralel işləyəndə bir-birinə mane olur, sıra dəyişəndə sınır. Hər testə lazım olanı fixture-da, API ilə, unikal adlarla yarat və teardown-da sil. İnsanların əllə dəyişdiyi ortaq staging serveri yox, idarə etdiyin mühit işlət, məsələn, lokal stack və ya ayrıca test bazası. Testləri test.describe.configure({ mode: "serial" }) ilə zəncirləmə: bir test sınanda qrupun qalanı ötürülür, bütün qrup isə birlikdə təkrarlanır.
Flakiness bug-dır. Flaky kimi göstərilən test sənə race barədə xəbər verir: cavab üçün çatışmayan gözləmə, animasiya, ortaq data, saatdan və ya testlərin sırasından asılılıq. Onu trace-də tap və testi və ya tətbiqi düzəlt. İndi düzəldə bilmədiyin testi açıq şəkildə karantinə al, məsələn, test.fixme və tiketlə; hamı nəticələri oxumağı dayandırana qədər onu təsadüfi sınmağa buraxma.
Sürət də vacib xüsusiyyətdir. storageState ilə bir dəfə daxil ol, datanı UI yox, request ilə yarat, fullyParallel ilə işə sal və CI-da shard et. Dəst komandanın pull request üçün gözləməyə hazır olduğundan uzun çəkirsə, insanlar onu ötürməyə başlayır və o zaman o, heç nəyi qorumur.
Hər ssenaridə əsas niyyəti yoxla. Yol boyu on beş şeyi yoxlayan testi oxumaq çətindir və on beş səbəbdən sınır. Ssenarinin nə üçün olduğunu yoxla (sifariş verildi, dəvət gəldi), üstəlik istifadəçinin oraya çatmaq üçün yolda görməli olduğunu.
Sağlam dəstin əlamətləri: qırmızı nəticəyə inanılır, uğursuzluq bir ssenariyə işarə edir, yeni funksionallıq isə on yox, bir-iki E2E test əlavə edir.
An E2E suite fails its purpose in two ways: it gets too slow to run on every change, or so flaky that a red run is ignored. Both are design decisions, not bad luck.
What stays out. Every validation message, every formatting rule, every API error code and every permission combination belongs in component tests with network mocks or in unit tests, where each case runs in milliseconds. An E2E test of a form checks that a valid submission goes through the whole stack and that one invalid input shows an error; the other rules are tested below. Third-party services, the internals of libraries and pixel-level styling (unless you run dedicated visual tests) stay out as well.
Data you own. Tests that share records interfere in parallel and break when the order changes. Create what each test needs in a fixture, through the API, with unique names, and delete it in the teardown. Run against an environment you control, such as a local stack or a dedicated test database, rather than a shared staging server that people change by hand. Avoid chaining tests with test.describe.configure({ mode: "serial" }): when one test fails, the rest of the group is skipped, and the whole group is retried together.
Flakiness is a bug. A test reported as flaky is telling you about a race: a missing wait for a response, an animation, shared data, a dependency on the clock or on the order of tests. Find it in the trace and fix the test or the app. A test you cannot fix now is quarantined openly, for example with test.fixme and a ticket, not left to fail at random until everyone stops reading the results.
Speed is a feature. Sign in once with storageState, create data through request instead of the UI, run with fullyParallel and shard on CI. If the suite takes longer than the team is willing to wait for a pull request, people start skipping it, and then it protects nothing.
One assertion of intent per journey. A test that checks fifteen things on the way is hard to read and fails for fifteen reasons. Assert what the journey is for (the order is placed, the invitation arrives), plus what the user must see along the way to get there.
The signs of a healthy suite: a red run is believed, a failure points to one journey, and a new feature adds one or two E2E tests, not ten.
Interview tips
30 saniyəlik cavab. "E2E test real tətbiqi real brauzerdə işə salır, ona görə hissələrin birlikdə işlədiyini sübut edir: build, routing, CSS, cookie-lər, API. O, yavaşdır və sınmağın daha çox yolu var, ona görə E2E testləri kritik ssenarilər üçün saxlayıram, kənar halları isə aşağı səviyyədə test edirəm. Playwright-də rol və label locator-ları işlədirəm, sabit gözləmələr əvəzinə auto-waiting və web-first assertion-lara güvənirəm, hər testə API fixture-ları ilə təzə data verirəm, storageState ilə bir dəfə daxil oluram, page.route ilə isə yalnız üçüncü tərəfləri və ya yaradılması çətin uğursuzluqları mock edirəm. CI-da ilk retry-da trace qeydə alıram və hər flaky nəticəyə bug kimi baxıram."
Gözlənilən suallar
- Niyə hər şeyi end-to-end test etməyək? Xərc: test başına saniyələr, flakiness üçün daha çox səbəb, qeyri-müəyyən uğursuzluqlar. Ssenarilər E2E-də, hallar daha sürətli testlərdə.
- Playwright vaxt problemlərindən necə qaçır? Hər action-dan əvvəl actionability yoxlamaları (görünən, stabil, event qəbul edən, aktiv, redaktə oluna bilən) və expect timeout-una qədər, default olaraq 5 saniyə, təkrar yoxlayan assertion-lar.
waitForTimeoutyalnız debug üçündür. - Testləri necə müstəqil saxlayırsan? Hər testə yeni browser context; fixture-larda API ilə yaradılan unikal data; testlərin sırasına və ortaq qeydlərə arxalanmamaq.
- Login-i necə həll edirsən? Daxil olub
storageStatesaxlayan setup project; project-lər ondan asılıdır; fayl git-ə düşmür; testlər server tərəfi state-i dəyişəndə hər worker-ə ayrı hesab. - E2E-də şəbəkəni mock edirsən? Default olaraq öz backend-ini yox; üçüncü tərəf servislərini və yaradılması çətin uğursuzluqları
page.routeilə, naviqasiyadan əvvəl qeydiyyata alaraq. - Yalnız CI-da sınan testi necə debug edirsən? Trace ilə: snapshot-lar, şəbəkə, konsol, işlədilən locator. Flaky testlər üçün
retain-on-failureilə qeydə al və sınana qədər təkrarla.
Bal itirməyə səbəb olan səhvlər
- Nümunələrdə
waitForTimeoutvə yaexpect(await locator.isVisible()).toBe(true). - Rol və ya label olduğu halda CSS və ya XPath selector-ları.
- Retry-ları flakiness üçün düzəliş adlandırmaq.
- Hər testdə UI ilə login olmaq və ya paralel worker-lər arasında dəyişkən bir hesabı paylaşmaq.
Senior səviyyəni göstərən məqamlar
Yalnız testdən yox, test dəstindən danış: hansı ssenarilər E2E əhatəsinə layiqdir, hansılar yox; test datası necə yaradılır və təmizlənir; hansı brauzerlər hər pull request-də, hansılar gecə işləyir; insanlar onu gözləməyi dayandırmamışdan əvvəl dəst nə qədər çəkə bilər; flaky test düzələnə qədər necə izlənir.
A 30-second answer. "An E2E test runs the real app in a real browser, so it proves the pieces work together: build, routing, CSS, cookies, the API. It is slow and has more ways to fail, so I keep E2E tests for the critical journeys and test edge cases lower down. With Playwright I use role and label locators, rely on auto-waiting and web-first assertions instead of fixed waits, give each test fresh data through API fixtures, sign in once with storageState, and mock only third parties or hard-to-produce failures with page.route. On CI I record traces on the first retry and treat every flaky result as a bug."
Questions you are likely to get
- Why not test everything end to end? Cost: seconds per test, more causes of flakiness, vague failures. Journeys in E2E, cases in faster tests.
- How does Playwright avoid timing problems? Actionability checks before each action (visible, stable, receives events, enabled, editable), and assertions that retry until the expect timeout, 5 seconds by default.
waitForTimeoutis for debugging only. - How do you keep tests independent? A new browser context per test; unique data created through the API in fixtures; no reliance on test order or shared records.
- How do you handle login? A setup project that signs in and saves
storageState; projects depend on it; the file is git-ignored; per-worker accounts when tests change server-side state. - Do you mock the network in E2E? Not your own backend by default; third-party services and hard-to-produce failures with
page.route, registered before navigation. - How do you debug a test that fails only on CI? The trace: snapshots, network, console, the locator used. For flaky tests, record with
retain-on-failureand repeat until it fails.
Mistakes that cost points
waitForTimeoutorexpect(await locator.isVisible()).toBe(true)in examples.- CSS or XPath selectors when a role or label exists.
- Calling retries a fix for flakiness.
- Logging in through the UI in every test, or sharing one mutable account between parallel workers.
Senior signal
Talk about the suite, not only the test: which journeys deserve E2E coverage and which do not, how test data is created and cleaned up, which browsers run on every pull request and which nightly, how long the suite may take before people stop waiting for it, and how a flaky test is tracked until it is fixed.
What to check when reviewing end-to-end tests
Yazmadığın Playwright testlərini — komanda yoldaşının pull request-ini, kitabxananın nümunəsini, AI assistentin təklifini — review edəndə bu siyahını işlət. Zəif E2E test nadir hallarda dərhal sınır; o, sonra, təsadüfi, CI-da sınır və qənaət etdiyindən çox vaxt aparır.
- Sabit gözləmələr və ya birdəfəlik yoxlamalar varmı?
waitForTimeout-u,expect(...)-ın içindəkiisVisible()-ı və əllə yazılmış polling dövrlərini axtar; onlarıawait expect(locator).toBeVisible()və yatoHaveURLkimi, expect timeout-una qədər təkrar yoxlayan web-first assertion-larla əvəz et. - Hər Playwright çağırışı await olunubmu? Çatışmayan
awaittestin action və ya assertion işləməmiş bitməsinə imkan verir;@typescript-eslint/no-floating-promisesqaydası və CI-dakıtscbunu tutur. - Locator-lar istifadəçinin gördüyünü təsvir edirmi? CSS class-ları, XPath və ya
nth()əvəzinə adlagetByRole-a,getByLabel-ə vəgetByText-ə üstünlük ver; zərərsiz markup dəyişikliyindən sonra testi fikrən işə sal: elementi yenə tapardımı? - Hər test öz datasını yaradırmı? Testlər arasında paylaşılan qeydləri, testlərin sırasına arxalanmanı və ya
mode: "serial"-ı axtar; data unikal adlarla fixture-dan və ya API çağırışından gəlməli və teardown-da silinməlidir. - Test hər dəfə UI ilə daxil olurmu? Login-in yeri
storageStateolan setup project-dir;playwright/.auth-un.gitignore-da olduğunu yoxla, çünki faylda sessiya cookie-ləri var. - Şəbəkə yalnız lazım olan yerdə mock olunubmu? Öz API-nin üzərində
page.routetesti yavaş komponent testinə çevirir; onun yeri üçüncü tərəf servisləri və yaradılması çətin uğursuzluqlardır vəpage.goto()-dan əvvəl qeydiyyata alınmalıdır. - Test hər kənar halı yox, ssenarini yoxlayırmı? Validasiya qaydaları və xəta kodları daha sürətli testlərə aiddir; E2E test istifadəçinin gəldiyi nəticəni yoxlamalıdır.
Use this list when you review Playwright tests you did not write: a teammate's pull request, an example from a library, an AI assistant's suggestion. A weak E2E test rarely fails at once; it fails later, at random, on CI, and costs more time than it saves.
- Are there fixed waits or one-shot checks? Search for
waitForTimeout,isVisible()insideexpect(...)and manual polling loops; replace them with web-first assertions such asawait expect(locator).toBeVisible()ortoHaveURL, which retry until the expect timeout. - Is every Playwright call awaited? A missing
awaitlets the test end before the action or assertion runs; the@typescript-eslint/no-floating-promisesrule andtscon CI catch it. - Do the locators describe what the user sees? Prefer
getByRolewith a name,getByLabelandgetByTextover CSS classes, XPath ornth(); run the test after a harmless markup change in your head: would it still find the element? - Does each test create its own data? Look for records shared between tests, reliance on test order or
mode: "serial"; data should come from a fixture or API call with unique names and be removed in teardown. - Does it sign in through the UI every time? Login belongs in a setup project with
storageState; check thatplaywright/.authis in.gitignore, because the file contains session cookies. - Is the network mocked only where it should be?
page.routeon your own API turns the test into a slow component test; it belongs on third-party services and hard-to-produce failures, registered beforepage.goto(). - Does the test check a journey, not every edge case? Validation rules and error codes belong in faster tests; an E2E test should assert the outcome the user came for.