Next Gen QA Β· Lead SDET Reference Β· Production Level

Playwright
API + UI Integration

Complete real-world guide to combining API and UI automation in a single Playwright framework β€” fixtures, auth, data flow, interception, sync & architecture.

🎭 Playwright Test ⚑ JavaScript πŸ”— API + UI Hybrid πŸ›οΈ Framework Architecture 🧠 10+ Years Patterns
01
01
🏒Why Real Companies Use API + UI Integration
Concept
Pure UI automation is slow, brittle, and expensive. Pure API testing misses rendering bugs. Hybrid testing uses each layer for what it does best β€” API for data setup/teardown, UI for visual & interaction verification.
Usage
At Freecharge/Axis Bank: recharge flows create transactions via API, then UI validates correct display on wallet dashboard. Saves 3–5 UI login steps per test run. A 200-test suite runs 40% faster vs pure UI approach.
Mistake
Using UI to create every piece of test data (clicking through 6 screens to create one user). This inflates test runtime and creates cascading failures when the creation UI breaks.
Interview
"API tests are 10-100x faster than UI. We use API for state setup and teardown, UI only for the specific user journey being tested. This keeps tests fast, reliable, and focused."
βš–οΈWhen to Prefer API over UI
Concept
Decision rule: If the user never sees it in the current test scenario, use API. Setup, teardown, data seeding, authentication, cleanup β€” always API. Only use UI for what you're explicitly testing.
Code
// ❌ BAD β€” UI to set up data for a different test goal
test('validate order total on checkout', async ({ page }) => {
  await page.goto('/login');
  await page.fill('#email', 'user@test.com');
  await page.fill('#pass', 'secret');
  await page.click('#login-btn');          // 3 unnecessary UI steps
  await page.goto('/products');
  await page.click('.product-card:first-child');  // 4 more steps
  await page.click('#add-to-cart');
  // ... total: 10+ steps before the REAL test even starts
});

// βœ… GOOD β€” API setup, UI for what matters
test('validate order total on checkout', async ({ page, request, authedPage }) => {
  const order = await createOrderViaAPI(request, { items: [{ sku: 'P001', qty: 2 }] });
  await authedPage.goto(`/orders/${order.id}`);  // jump straight to goal
  await expect(authedPage.locator('.order-total')).toHaveText(`β‚Ή${order.total}`);
});
Interview
"The test pyramid says: many unit tests, fewer integration, even fewer E2E. Hybrid API+UI is the 'smart E2E' layer β€” full browser validation without the full browser setup cost."
πŸ“Š API vs UI vs Hybrid β€” Decision Matrix
ConcernPure UIPure APIAPI + UI Hybrid βœ…
SpeedSlow (5–30s/test)Fast (<1s)Fast (2–5s/test)
Test Data SetupFragile, slowReliable, fastAPI-seeded βœ…
UI Rendering CheckYesNoYes (focused)
Auth SetupRepeat login every testToken injectionstorageState reuse
Flakiness RiskHigh (UI timing)Very lowLow (minimal UI)
CleanupOften skippedEasy via DELETEAPI cleanup in afterEach
02
02
🧩page & request Fixtures β€” What They Really Are
Concept
page = Playwright Page instance with its own browser context. request = APIRequestContext with baseURL from config. Both are test-scoped by default β€” fresh per test, auto-disposed.
Code
// Built-in fixtures β€” both available in same test
import { test, expect } from '@playwright/test';

test('use both in one test', async ({ page, request }) => {
  // request β€” pure HTTP, no browser
  const res  = await request.post('/api/users', { data: payload });
  const user = await res.json();

  // page β€” browser, inherits baseURL from config for navigation
  await page.goto(`/users/${user.id}`);
  await expect(page.locator('h1')).toHaveText(user.name);
});

// KEY: request fixture uses baseURL from playwright.config
// KEY: page fixture is a fresh browser tab per test
// KEY: they share NO session β€” separate contexts by default
Mistake
Assuming page and request share cookies/sessions β€” they don't. The request fixture is a separate HTTP context, not linked to the browser's cookie jar.
πŸ”§Custom Fixture β€” The Power Pattern
Concept
test.extend() lets you define reusable fixtures that compose multiple concerns: auth, services, pre-seeded data. Tests import your test object, not Playwright's base one.
Code
// src/fixtures/base.fixture.js
import { test as base, expect } from '@playwright/test';
import { UserService   } from '../api/UserService.js';
import { OrderService  } from '../api/OrderService.js';
import { LoginPage     } from '../pages/LoginPage.js';
import { getAuthState  } from '../helpers/auth.helper.js';

export const test = base.extend({

  // API service fixtures
  userService:  async ({ request }, use) => await use(new UserService(request)),
  orderService: async ({ request }, use) => await use(new OrderService(request)),

  // Pre-authenticated browser page
  authedPage: async ({ browser }, use) => {
    const ctx  = await browser.newContext({
      storageState: await getAuthState()  // inject saved session
    });
    const pg   = await ctx.newPage();
    await use(pg);
    await ctx.close();                     // always cleanup
  },

  // Pre-seeded user β€” create via API, pass to test
  seededUser: async ({ userService }, use) => {
    const user = await userService.createAndParse(buildUser());
    await use(user);                        // test runs
    await userService.remove(user.id);     // auto cleanup
  },
});

export { expect };
Usage
Tests that import from base.fixture.js get all these as named params. No boilerplate per test file. The seededUser fixture auto-creates and auto-deletes the user around each test.
Interview
"Fixtures in Playwright work like dependency injection. The use() function is the yield point β€” code before use() runs before the test, code after runs as teardown. This is how we get zero-boilerplate cleanup."
πŸ”€ Sharing Data Between API & UI β€” Patterns
// PATTERN 1 β€” Pass API response ID directly to UI navigation
test('API β†’ UI data handoff', async ({ userService, authedPage }) => {
  const user = await userService.createAndParse({ name: 'Amir Khan', email: 'amir@qa.com' });

  // ID from API used directly in URL
  await authedPage.goto(`/admin/users/${user.id}`);
  await expect(authedPage.locator('[data-testid="user-email"]')).toHaveText(user.email);
});

// PATTERN 2 β€” Use fixture with test-level cleanup tracking
test('pre-seeded fixture', async ({ seededUser, authedPage }) => {
  // seededUser already created before test, auto-deleted after
  await authedPage.goto(`/users/${seededUser.id}/profile`);
  await expect(authedPage.locator('.profile-name')).toHaveText(seededUser.name);
});

// PATTERN 3 β€” test.info() to attach API data to report
test('attach API data to trace', async ({ request, page }, testInfo) => {
  const res  = await request.get('/api/dashboard/stats');
  const data = await res.json();
  await testInfo.attach('api-stats-response', {
    body: JSON.stringify(data, null, 2),
    contentType: 'application/json'
  });
  await page.goto('/dashboard');
  await expect(page.locator('.stat-total-users')).toHaveText(`${data.totalUsers}`);
});
03
03
🌱Create Test Data via API β€” Dynamic Handling
Code
// src/helpers/testSetup.helper.js
import { buildUser, buildOrder } from '../factories';

export async function seedCheckoutScenario(request, overrides = {}) {
  // Step 1 β€” create user
  const userRes  = await request.post('/api/users', {
    data: buildUser(overrides.user)
  });
  const user = await userRes.json();

  // Step 2 β€” add wallet balance
  await request.post(`/api/users/${user.id}/wallet/credit`, {
    data: { amount: overrides.walletBalance ?? 500 }
  });

  // Step 3 β€” create pending order
  const orderRes = await request.post('/api/orders', {
    data: buildOrder({ userId: user.id, ...overrides.order })
  });
  const order = await orderRes.json();

  return { user, order };   // return all IDs for UI + cleanup
}

// In test file
test('checkout with wallet balance', async ({ request, authedPage }) => {
  const { user, order } = await seedCheckoutScenario(request, {
    walletBalance: 1000, order: { items: ['PROD-42'] }
  });
  await authedPage.goto(`/checkout/${order.id}`);
  await expect(authedPage.locator('.wallet-balance')).toContainText('β‚Ή1000');
});
Mistake
Not tracking created IDs for cleanup. If a test fails mid-way and cleanup never runs, QA DB fills with stale data, causing future test collisions. Always use try/finally or fixture-based cleanup.
Interview
"We use a 'scenario builder' pattern β€” one function that creates an entire business scenario (user + wallet + order + promo) via API and returns a typed context object. UI test just gets the IDs and navigates."
πŸ“¨Pass API Response Data into UI Tests
Code
// beforeEach β€” seed per test, teardown guaranteed
let testContext = {};

test.beforeEach(async ({ request }) => {
  const res = await request.post('/api/products', {
    data: { name: 'Test Product', price: 499, stock: 10 }
  });
  testContext.product = await res.json();
  testContext.createdIds = [testContext.product.id];
});

test.afterEach(async ({ request }) => {
  // cleanup all IDs created during test
  for (const id of testContext.createdIds) {
    await request.delete(`/api/products/${id}`).catch(() => {});
  }
  testContext = {};
});

test('product price displays correctly', async ({ authedPage }) => {
  const { product } = testContext;
  await authedPage.goto(`/products/${product.id}`);
  await expect(authedPage.locator('[data-testid="price"]'))
    .toHaveText(`β‚Ή${product.price.toLocaleString('en-IN')}`);
});
Mistake
Sharing testContext across parallel workers β€” module-level objects are not shared between workers. Use fixture-scoped variables instead of module-level let.
04
04
⚑Login via API β€” storageState Injection
Concept
Instead of filling login form on every test, call the auth API once in globalSetup, save cookies + localStorage to auth.json, then inject that state into every browser context. UI tests start already logged in.
Code
// src/global/globalSetup.js
import { request } from '@playwright/test';
import { config } from '../config/env.config.js';
import fs from 'fs/promises';

export default async function globalSetup() {
  const ctx = await request.newContext({ baseURL: config.baseUrl });

  // Option A β€” Form-based login (sets session cookie)
  await ctx.post('/auth/login', {
    form: { email: process.env.TEST_EMAIL, password: process.env.TEST_PASS }
  });
  await ctx.storageState({ path: './auth-state/user.json' });

  // Option B β€” JWT login (save token for API, cookie for UI)
  const res   = await ctx.post('/auth/jwt/login', {
    data: { email: process.env.ADMIN_EMAIL, password: process.env.ADMIN_PASS }
  });
  const { access_token, refresh_token } = await res.json();
  process.env.ACCESS_TOKEN = access_token;
  await fs.writeFile('./auth-state/tokens.json',
    JSON.stringify({ access_token, refresh_token })
  );
  await ctx.dispose();
}

// playwright.config.js
export default defineConfig({
  use: {
    storageState: './auth-state/user.json'  // applied to ALL page fixtures
  },
  globalSetup: './src/global/globalSetup.js',
});
Usage
Every test's page fixture now opens the browser already authenticated. Zero login steps in test code. For multi-role testing (admin vs user), create separate auth-state/admin.json and auth-state/user.json.
Mistake
Committing auth-state/*.json to git β€” contains live session tokens. Add to .gitignore. Regenerate in CI via globalSetup. Also: not refreshing tokens when they expire (run time > token lifetime).
Interview
"storageState captures cookies, localStorage, and sessionStorage into a JSON file. When loaded into a browser context, the browser behaves as if the user already completed login β€” even SSO flows with complex redirect chains."
🎭Multi-Role Auth & Token Injection Patterns
Code
// src/helpers/auth.helper.js β€” multi-role manager
import { request } from '@playwright/test';
import { config } from '../config/env.config.js';
import path from 'path';
import fs from 'fs/promises';

const ROLES = {
  admin:   { email: process.env.ADMIN_EMAIL,  pass: process.env.ADMIN_PASS  },
  user:    { email: process.env.USER_EMAIL,   pass: process.env.USER_PASS   },
  viewer:  { email: process.env.VIEWER_EMAIL, pass: process.env.VIEWER_PASS },
};

export async function setupAuthState(role = 'user') {
  const statePath = path.join('./auth-state', `${role}.json`);
  const creds     = ROLES[role];
  const ctx       = await request.newContext({ baseURL: config.baseUrl });
  await ctx.post('/auth/login', { data: creds });
  await ctx.storageState({ path: statePath });
  await ctx.dispose();
  return statePath;
}

// Inject JWT into localStorage for SPA apps
export async function injectToken(page, token) {
  await page.addInitScript(({ token }) => {
    window.localStorage.setItem('access_token', token);
    window.localStorage.setItem('auth_state', 'authenticated');
  }, { token });
}

// Fixture β€” admin-authenticated page
adminPage: async ({ browser }, use) => {
  const statePath = await setupAuthState('admin');
  const ctx = await browser.newContext({ storageState: statePath });
  await use(await ctx.newPage());
  await ctx.close();
},
Interview
"page.addInitScript() runs before any page script β€” ideal for injecting tokens into localStorage before the SPA boots. The SPA reads localStorage on init and considers itself authenticated."
05
05
πŸ”„ Cross-Layer Validation β€” Complete Strategy
// Cross-validation: API data β†’ UI display β†’ back to API
test('dashboard stats match API source of truth', async ({ request, authedPage }) => {
  // Step 1: Fetch ground truth from API
  const apiRes  = await request.get('/api/dashboard/stats');
  expect(apiRes).toBeOK();
  const apiData = await apiRes.json();

  // Step 2: Navigate UI and extract displayed values
  await authedPage.goto('/dashboard');
  await authedPage.waitForSelector('[data-testid="stats-loaded"]'); // wait for async load

  const uiTotalUsers  = await authedPage.locator('[data-testid="total-users"]').textContent();
  const uiTotalOrders = await authedPage.locator('[data-testid="total-orders"]').textContent();

  // Step 3: Cross-validate (parse UI text to number)
  expect(parseInt(uiTotalUsers, 10)).toBe(apiData.totalUsers);
  expect(parseInt(uiTotalOrders, 10)).toBe(apiData.totalOrders);
});

// Validate UI table rows match API list
test('user list UI matches API data', async ({ request, authedPage }) => {
  const res   = await request.get('/api/users?page=1&limit=10');
  const { data: users } = await res.json();

  await authedPage.goto('/admin/users');
  const rows = authedPage.locator('[data-testid="user-row"]');
  await expect(rows).toHaveCount(users.length);

  // Validate each row's email matches API
  for (let i = 0; i < users.length; i++) {
    await expect(rows.nth(i).locator('.email')).toHaveText(users[i].email);
  }
});

// After UI action β€” verify via API (reverse cross-validation)
test('UI delete β†’ verify gone via API', async ({ request, authedPage, seededUser }) => {
  await authedPage.goto(`/admin/users/${seededUser.id}`);
  await authedPage.click('[data-testid="delete-btn"]');
  await authedPage.click('[data-testid="confirm-delete"]');
  await expect(authedPage.locator('.success-toast')).toBeVisible();

  // Cross-validate β€” API should return 404 now
  const apiCheck = await request.get(`/api/users/${seededUser.id}`);
  expect(apiCheck.status()).toBe(404); // API confirms deletion
});
πŸ’‘ Strategy: API is the source of truth. UI must reflect it. Always validate both directions: API creates β†’ UI shows it, UI deletes β†’ API confirms it's gone.
06
06
🎬 Scenario 1: Create User via API β†’ Login via UI β†’ Validate Dashboard
// tests/scenarios/user-dashboard.spec.js
import { test, expect } from '../fixtures/base.fixture.js';
import { buildUser } from '../factories';
import { LoginPage     } from '../pages/LoginPage.js';
import { DashboardPage } from '../pages/DashboardPage.js';

test('@smoke create user via API β†’ login via UI β†’ verify dashboard',
  async ({ page, userService }) => {
  const password = 'Test@12345';
  let userId;

  await test.step('Step 1: Create user via API', async () => {
    const user = await userService.createAndParse(
      buildUser({ password, role: 'member', verified: true })
    );
    userId = user.id;
    expect(user.id).toBeDefined();
    // Store for cleanup
    Object.assign(test.info(), { userId });
  });

  await test.step('Step 2: Login via UI (no storageState β€” testing login flow itself)',
    async () => {
    const loginPage = new LoginPage(page);
    await loginPage.goto();
    await loginPage.loginWith(process.env.TEST_EMAIL, password);
    await expect(page).toHaveURL(/\/dashboard/);
  });

  await test.step('Step 3: Validate dashboard has correct user context', async () => {
    const dashPage = new DashboardPage(page);
    await dashPage.waitForLoad();
    await expect(dashPage.welcomeMessage).toContainText(process.env.TEST_NAME);
    await expect(dashPage.memberBadge).toBeVisible();
  });

  // Step 4: Cleanup via API
  await userService.remove(userId);
});
πŸ›’ Scenario 2: Create Order via API β†’ Validate Order in UI
// tests/scenarios/order-display.spec.js
test('@regression order details display correctly on UI',
  async ({ authedPage, orderService }) => {
  let orderId;

  await test.step('Create order with 3 items via API', async () => {
    const order = await orderService.createAndParse({
      items: [
        { sku: 'MOBILE-001', qty: 1, price: 12999 },
        { sku: 'COVER-007',  qty: 2, price: 299   },
        { sku: 'SCREEN-003', qty: 1, price: 499   },
      ],
      coupon: 'FLAT10',
    });
    orderId = order.id;
    // Verify API computed total correctly before UI check
    expect(order.total).toBe(13796);   // (12999+598+499) - 10% = 13596 .. verify this
    expect(order.couponApplied).toBe(true);
  });

  await test.step('Navigate to order detail page', async () => {
    await authedPage.goto(`/orders/${orderId}`);
    await authedPage.waitForLoadState('networkidle');
  });

  await test.step('Validate order summary on UI matches API', async () => {
    await expect(authedPage.locator('[data-testid="order-id"]'))
      .toHaveText(`#${orderId}`);
    await expect(authedPage.locator('[data-testid="order-status"]'))
      .toHaveText('Pending');
    await expect(authedPage.locator('[data-testid="coupon-badge"]'))
      .toBeVisible();
    const lineItems = authedPage.locator('[data-testid="order-item"]');
    await expect(lineItems).toHaveCount(3);
  });

  await test.step('Cleanup: cancel order via API', async () => {
    await orderService.cancel(orderId);
  });
});
πŸ’³ Scenario 3: E2E Recharge Flow β€” Freecharge-style (API seed β†’ UI complete β†’ API verify)
test('@critical mobile recharge β€” complete flow',
  async ({ authedPage, request, userService }) => {
  let txnId;
  const mobileNumber = '9999988888';
  const rechargeAmt  = 199;

  // API: seed wallet balance
  const user = await userService.getByEmail(process.env.TEST_EMAIL);
  await request.post(`/api/wallet/${user.id}/credit`, {
    data: { amount: 500, note: 'test-seed' }
  });

  // UI: perform recharge
  await authedPage.goto('/recharge');
  await authedPage.fill('[data-testid="mobile-input"]', mobileNumber);
  await authedPage.click('[data-testid="plan-199"]');
  await authedPage.click('[data-testid="pay-wallet"]');

  // Wait for transaction ID to appear (network + render)
  const txnLocator = authedPage.locator('[data-testid="txn-id"]');
  await expect(txnLocator).toBeVisible({ timeout: 10000 });
  txnId = await txnLocator.textContent();

  // API: cross-validate transaction was actually created
  const txnRes = await request.get(`/api/transactions/${txnId}`);
  const txn    = await txnRes.json();
  expect(txn.status).toBe('SUCCESS');
  expect(txn.amount).toBe(rechargeAmt);
  expect(txn.mobile).toBe(mobileNumber);

  // API: verify wallet balance deducted
  const walletRes = await request.get(`/api/wallet/${user.id}`);
  const wallet    = await walletRes.json();
  expect(wallet.balance).toBe(500 - rechargeAmt); // 301
});
07
07
πŸ•ΈοΈpage.route() β€” Core Patterns
Concept
page.route(pattern, handler) intercepts network calls before they leave the browser. Handlers can: fulfill (return mock), continue (pass-through), abort (block), or modify the real response.
Code
// 1. FULFILL β€” return mock response (no server call)
await page.route('**/api/users**', async route => {
  await route.fulfill({
    status:      200,
    contentType: 'application/json',
    body:        JSON.stringify({ data: [{ id: 'u1', name: 'Mock User' }] })
  });
});

// 2. ABORT β€” block analytics / ads / 3rd-party trackers
await page.route(/google-analytics|hotjar|intercom/, r => r.abort());

// 3. MODIFY β€” intercept real response and alter fields
await page.route('**/api/feature-flags', async route => {
  const res  = await route.fetch();           // get real response
  const body = await res.json();
  body.newCheckoutEnabled = true;              // inject feature flag
  await route.fulfill({ response: res, body: JSON.stringify(body) });
});

// 4. CONDITIONAL β€” mock only POST, pass through GET
await page.route('**/api/payments', async route => {
  if (route.request().method() === 'POST') {
    await route.fulfill({
      status: 200,
      body:   JSON.stringify({ txnId: 'MOCK-TXN-001', status: 'SUCCESS' })
    });
  } else {
    await route.continue();                  // let GET pass through
  }
});
Usage
Use abort to kill slow trackers (saves 200–500ms/test). Use fulfill to test error states (500, 401) without breaking the real backend. Use modify to enable unreleased feature flags.
Mistake
Not removing routes after a test β€” page.route() is cumulative in the same context. Use page.unroute() or scope routes inside tests with fresh page per test.
πŸ“‘Capture & Assert Network Requests
Code
// Capture outgoing request body from UI action
test('verify checkout payload sent to payment API', async ({ authedPage }) => {
  let capturedPayload;

  await authedPage.route('**/api/payments/initiate', async route => {
    capturedPayload = JSON.parse(route.request().postData() || '{}');
    await route.continue();  // let real request proceed
  });

  await authedPage.goto('/checkout/confirm');
  await authedPage.click('[data-testid="pay-now"]');

  // Wait for request to fire
  await authedPage.waitForResponse('**/api/payments/initiate');

  expect(capturedPayload).toMatchObject({
    method:   'WALLET',
    currency: 'INR',
    orderId:  expect.any(String),
  });
});

// Wait for specific API call triggered by UI
test('search triggers correct API call', async ({ authedPage }) => {
  await authedPage.goto('/search');

  const [response] = await Promise.all([
    authedPage.waitForResponse(r =>
      r.url().includes('/api/search') && r.status() === 200
    ),
    authedPage.fill('[data-testid="search-input"]', 'iPhone'),
    authedPage.keyboard.press('Enter'),
  ]);
  const apiResult = await response.json();
  expect(apiResult.results.length).toBeGreaterThan(0);
});
Interview
"page.route intercepts at browser level before DNS/TCP β€” ideal for mocking external payment gateways. waitForResponse lets us assert the actual API response triggered by a UI click without re-querying the API separately."
08
08
⏳API β†’ UI Propagation Delays
Concept
After creating data via API, UI may not immediately show it β€” cache TTL, SSE lag, polling intervals, React re-renders. Never use page.waitForTimeout(2000). Always use event-based waits.
Code
// ❌ NEVER β€” flaky hard wait
await page.waitForTimeout(2000);  // time bomb

// βœ… Wait for element with retry-safe assertion
await expect(page.locator('[data-testid="new-user-row"]'))
  .toBeVisible({ timeout: 8000 });  // Playwright polls until visible

// βœ… Wait for specific network response after API creates data
const [listResponse] = await Promise.all([
  page.waitForResponse('**/api/users?**'),  // UI refetches the list
  page.click('[data-testid="refresh-btn"]'),
]);
expect(listResponse.status()).toBe(200);

// βœ… Poll API until resource is ready (async processing)
async function waitForJobCompletion(request, jobId, maxMs = 30000) {
  const deadline = Date.now() + maxMs;
  while (Date.now() < deadline) {
    const res = await request.get(`/api/jobs/${jobId}`);
    const job = await res.json();
    if (job.status === 'completed') return job;
    if (job.status === 'failed')    throw new Error(`Job failed: ${job.error}`);
    await new Promise(r => setTimeout(r, 500));  // poll every 500ms
  }
  throw new Error(`Job ${jobId} did not complete in ${maxMs}ms`);
}

// βœ… Wait for URL change after login redirect
await page.waitForURL(/\/dashboard/, { timeout: 10000 });

// βœ… waitForLoadState β€” choose the right one
await page.waitForLoadState('networkidle');  // ← for pages with many XHR calls
await page.waitForLoadState('domcontentloaded'); // ← for SPAs
Mistake
Using networkidle everywhere β€” it waits for zero network activity for 500ms. On live chat or analytics-heavy pages, it never fires. Use targeted waitForResponse or element visibility instead.
Interview
"Flakiness from hard waits is test debt. Every waitForTimeout is a future incident. Playwright's auto-waiting on locator assertions (toBeVisible, toHaveText) handles most cases β€” the key is trusting the framework."
πŸ”Sync Anti-Patterns & Fixes
Code
// ANTI-PATTERN 1: Race condition β€” UI navigates before API response processed
// ❌ BAD
await request.post('/api/orders', { data: payload });
await authedPage.goto('/orders');  // may load before order is in DB!
expect(authedPage.locator('.order-row')).toHaveCount(1); // FLAKY

// βœ… GOOD β€” await full API response before navigating
const res   = await request.post('/api/orders', { data: payload });
const order = await res.json();  // confirms write completed
await authedPage.goto(`/orders/${order.id}`); // navigate to specific resource

// ANTI-PATTERN 2: Parallel API + UI without Promise.all
// ❌ BAD β€” sequential when it could be parallel
await request.get('/api/orders');
await authedPage.goto('/orders');

// βœ… GOOD β€” fire both at the same time
const [apiRes] = await Promise.all([
  request.get('/api/orders'),
  authedPage.goto('/orders'),
]);

// ANTI-PATTERN 3: Forgetting Playwright auto-waits
// ❌ BAD β€” manually waiting before Playwright already does
await page.waitForSelector('.submit-btn');  // redundant
await page.click('.submit-btn');           // click already waits

// βœ… GOOD
await page.click('.submit-btn');  // auto-waits for visible+enabled
09
09
πŸš€Reduce UI Steps via API β€” Timing Comparison
Code
// BEFORE β€” pure UI (12 steps, ~18s)
test('[OLD] create product and verify price', async ({ page }) => {
  await page.goto('/login');
  await page.fill('#email', 'admin@test.com');
  await page.fill('#pass',  'secret');
  await page.click('#login');              // 2s
  await page.goto('/admin/products/new');
  await page.fill('#name',  'Test Product');
  await page.fill('#price', '499');
  await page.click('#save');               // 3s
  // ... verify steps
  // Total: ~18s
});

// AFTER β€” API + UI hybrid (3 UI steps, ~3s)
test('[NEW] verify product price on product page',
  async ({ authedPage, request }) => {
  const res     = await request.post('/api/products', {
    data: { name: 'Test Product', price: 499 } // <200ms
  });
  const product  = await res.json();
  await authedPage.goto(`/products/${product.id}`);     // <1s (already authed)
  await expect(authedPage.locator('[data-testid="price"]'))
    .toHaveText('β‚Ή499');                              // <500ms
  await request.delete(`/api/products/${product.id}`); // <200ms cleanup
  // Total: ~2s ← 9x faster
});
Usage
Real metric: A 100-test suite at Freecharge went from 28 minutes (pure UI) to 7 minutes (hybrid API+UI) by moving login + data setup to API. Same coverage, 4x faster CI feedback.
πŸ”€Parallel Execution Strategy
Code
// playwright.config.js β€” parallel tuning
export default defineConfig({
  workers:       process.env.CI ? 4 : 2,
  fullyParallel: true,
  retries:       process.env.CI ? 1 : 0,

  projects: [
    {
      name:      'chromium-api-ui',
      testMatch: 'tests/**/*.spec.js',
      use:       { ...devices['Desktop Chrome'] },
    }
  ],
});

// Worker-safe unique data with testInfo
test('parallel safe', async ({ request }, testInfo) => {
  const uid  = `w${testInfo.workerIndex}_${Date.now()}`;
  const user = await (
    await request.post('/api/users', {
      data: { email: `${uid}@test.com` }
    })
  ).json();
  // test code...
});

// Parallelize setup with Promise.all for speed
const [userA, userB, product] = await Promise.all([
  userService.createAndParse(buildUser({ role: 'buyer'  })),
  userService.createAndParse(buildUser({ role: 'seller' })),
  productService.createAndParse(buildProduct()),
]);
// Creates 3 resources concurrently β€” 3x faster than sequential
Interview
"Promise.all for parallel API setup is a core optimization. 3 API calls at 200ms each = 200ms total instead of 600ms sequential. On 50 tests, that's 20 seconds saved just in setup."
10
10
πŸ”Trace Viewer & Playwright Inspector
Code
// playwright.config.js β€” trace on failure only (CI-friendly)
use: {
  trace:      'retain-on-failure',   // only save when test fails
  screenshot: 'only-on-failure',
  video:      'retain-on-failure',
},

// Open trace file after failure:
// npx playwright show-trace test-results/trace.zip

// Programmatically start trace for a specific test
test('debug this specific test', async ({ page, context }) => {
  await context.tracing.start({ screenshots: true, snapshots: true, sources: true });
  // ... test code ...
  await context.tracing.stop({ path: './debug-trace.zip' });
});

// Capture console errors from browser during API-triggered UI updates
test('detect console errors during recharge', async ({ page }) => {
  const consoleErrors = [];
  page.on('console', msg => {
    if (msg.type() === 'error') consoleErrors.push(msg.text());
  });
  page.on('pageerror', err => consoleErrors.push(err.message));

  await page.goto('/dashboard');
  await page.waitForLoadState('networkidle');

  expect(consoleErrors, `Console errors: ${consoleErrors.join(', ')}`)
    .toHaveLength(0);
});
πŸ“‹Network Logging & API Call Assertions
Code
// Log all network activity during a test (useful for debugging flakiness)
test.beforeEach(async ({ page }) => {
  if (process.env.DEBUG_NETWORK) {
    page.on('request',  req  => console.log(`β†’ ${req.method()} ${req.url()}`));
    page.on('response', resp =>
      console.log(`← ${resp.status()} ${resp.url()} (${resp.timing().responseEnd}ms)`)
    );
    page.on('requestfailed', req =>
      console.error(`βœ— FAILED: ${req.url()} β€” ${req.failure()?.errorText}`)
    );
  }
});

// Attach failed API responses to test report
test.afterEach(async ({ page }, testInfo) => {
  if (testInfo.status !== 'passed') {
    const screenshot = await page.screenshot({ fullPage: true });
    await testInfo.attach('failure-screenshot', {
      body: screenshot, contentType: 'image/png'
    });
  }
});

// DEBUG env tricks:
// PWDEBUG=1       npx playwright test      ← opens inspector
// DEBUG=pw:api    npx playwright test      ← logs all HTTP calls
// DEBUG_NETWORK=1 npx playwright test      ← your custom logs above
// --headed --slowmo=500                   ← watch it run visually
Interview
"Trace viewer shows every DOM mutation, network call, and screenshot in a timeline β€” it's like a DVR for your test. For API failures, DEBUG=pw:api logs the full request/response at the protocol level."
11
11
πŸ“ Complete Folder Structure
playwright-api-ui-framework/
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ api/                         ← API service classes
β”‚   β”‚   β”œβ”€β”€ UserService.js           ← user CRUD, getByEmail, promote
β”‚   β”‚   β”œβ”€β”€ OrderService.js          ← order CRUD, cancel, getByUser
β”‚   β”‚   β”œβ”€β”€ AuthService.js           ← login, refresh, logout
β”‚   β”‚   └── WalletService.js         ← credit, debit, getBalance
β”‚   β”‚
β”‚   β”œβ”€β”€ pages/                       ← Page Object Model classes
β”‚   β”‚   β”œβ”€β”€ BasePage.js              ← common: goto, waitForLoad, getTitle
β”‚   β”‚   β”œβ”€β”€ LoginPage.js             ← loginWith(), socialLogin()
β”‚   β”‚   β”œβ”€β”€ DashboardPage.js
β”‚   β”‚   β”œβ”€β”€ OrdersPage.js
β”‚   β”‚   └── CheckoutPage.js
β”‚   β”‚
β”‚   β”œβ”€β”€ fixtures/
β”‚   β”‚   └── base.fixture.js          ← test.extend: userService, authedPage, seededUser
β”‚   β”‚
β”‚   β”œβ”€β”€ factories/
β”‚   β”‚   β”œβ”€β”€ user.factory.js          ← buildUser, buildAdminUser
β”‚   β”‚   β”œβ”€β”€ order.factory.js         ← buildOrder, buildOrderWithItems
β”‚   β”‚   └── index.js                 ← barrel export
β”‚   β”‚
β”‚   β”œβ”€β”€ helpers/
β”‚   β”‚   β”œβ”€β”€ auth.helper.js           ← setupAuthState, injectToken, getToken
β”‚   β”‚   β”œβ”€β”€ request.helper.js        ← retryRequest, loggedRequest
β”‚   β”‚   └── assert.helper.js         ← assertPagination, assertSchema
β”‚   β”‚
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── env.config.js            ← dev/qa/prod baseURL + credentials
β”‚   β”‚
β”‚   └── global/
β”‚       β”œβ”€β”€ globalSetup.js           ← login once, save auth-state
β”‚       └── globalTeardown.js        ← cleanup seeded test data
β”‚
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ api/                         ← pure API tests
β”‚   β”‚   β”œβ”€β”€ users.api.spec.js
β”‚   β”‚   └── orders.api.spec.js
β”‚   β”œβ”€β”€ ui/                          ← pure UI tests
β”‚   β”‚   └── navigation.ui.spec.js
β”‚   └── scenarios/                   ← hybrid API+UI integration tests
β”‚       β”œβ”€β”€ user-dashboard.spec.js
β”‚       β”œβ”€β”€ order-flow.spec.js
β”‚       └── recharge-flow.spec.js
β”‚
β”œβ”€β”€ auth-state/                      ← .gitignore this!
β”‚   β”œβ”€β”€ user.json
β”‚   └── admin.json
β”‚
β”œβ”€β”€ playwright.config.js
β”œβ”€β”€ .env                             ← secrets (never commit)
└── package.json
πŸ”ŒSample API Service Class
Code
// src/api/UserService.js
import { buildUser } from '../factories';
import { expect } from '@playwright/test';

export class UserService {
  constructor(request) {
    this.request = request;
    this.base    = '/api/v2/users';
  }

  async getAll(params = {}) {
    return this.request.get(this.base, { params });
  }

  async getById(id) {
    return this.request.get(`${this.base}/${id}`);
  }

  async getByEmail(email) {
    const res  = await this.request.get(this.base, {
      params: { email, limit: 1 }
    });
    const { data } = await res.json();
    return data[0] ?? null;
  }

  async create(data) {
    return this.request.post(this.base, { data });
  }

  async createAndParse(data = {}) {
    const payload = { ...buildUser(), ...data };
    const res     = await this.create(payload);
    expect(res.status(), 'User creation failed').toBe(201);
    return res.json();
  }

  async update(id, data) {
    return this.request.patch(`${this.base}/${id}`, { data });
  }

  async remove(id) {
    const res = await this.request.delete(`${this.base}/${id}`);
    if (![204, 404].includes(res.status())) {
      console.warn(`⚠ Cleanup: failed to delete user ${id}`);
    }
  }

  async promoteToAdmin(id) {
    const res = await this.request.post(`${this.base}/${id}/promote`);
    expect(res).toBeOK();
    return res.json();
  }
}
πŸ“„Sample Page Object Model (POM)
Code
// src/pages/BasePage.js
export class BasePage {
  constructor(page) { this.page = page; }
  async goto(path = '/') { await this.page.goto(path); }
  async waitForLoad() {
    await this.page.waitForLoadState('domcontentloaded');
  }
  get pageTitle() { return this.page.title(); }
}

// src/pages/LoginPage.js
import { BasePage } from './BasePage.js';

export class LoginPage extends BasePage {
  constructor(page) {
    super(page);
    // Locators as getters (re-evaluated each call = no stale elements)
    this.emailInput  = page.locator('[data-testid="email-input"]');
    this.passInput   = page.locator('[data-testid="password-input"]');
    this.submitBtn   = page.locator('[data-testid="login-submit"]');
    this.errorMsg    = page.locator('[data-testid="login-error"]');
  }

  async goto() { await this.page.goto('/login'); }

  async loginWith(email, password) {
    await this.emailInput.fill(email);
    await this.passInput.fill(password);
    await Promise.all([
      this.page.waitForURL(/\/dashboard/),
      this.submitBtn.click(),
    ]);
  }

  async expectError(message) {
    await expect(this.errorMsg).toContainText(message);
  }
}
🎯 Complete Combined Test β€” API + UI + POM + Fixture
// tests/scenarios/order-flow.spec.js
import { test, expect } from '../../src/fixtures/base.fixture.js';
import { OrdersPage   } from '../../src/pages/OrdersPage.js';
import { CheckoutPage } from '../../src/pages/CheckoutPage.js';
import { buildOrder  } from '../../src/factories';

test.describe('Order Management @regression', () => {
  test('complete order lifecycle β€” API seed β†’ UI verify β†’ UI action β†’ API confirm',
    async ({ authedPage, orderService }) => {

    let orderId;

    /* ── SETUP via API ───────────────────────────────── */
    await test.step('Seed: create pending order via API', async () => {
      const order = await orderService.createAndParse(
        buildOrder({ status: 'pending', amount: 1499 })
      );
      orderId = order.id;
      expect(orderId).toBeDefined();
    });

    /* ── UI VERIFICATION ─────────────────────────────── */
    const ordersPage = new OrdersPage(authedPage);
    await test.step('UI: navigate and verify order card shows pending', async () => {
      await ordersPage.goto();
      const orderCard = await ordersPage.findOrderCard(orderId);
      await expect(orderCard.locator('.status')).toHaveText('Pending');
      await expect(orderCard.locator('.amount')).toHaveText('β‚Ή1,499');
    });

    /* ── UI ACTION ───────────────────────────────────── */
    const checkoutPage = new CheckoutPage(authedPage);
    await test.step('UI: complete payment via checkout page', async () => {
      await ordersPage.clickPayNow(orderId);
      await checkoutPage.selectWallet();
      await checkoutPage.confirm();
      await expect(authedPage.locator('.success-banner')).toBeVisible();
    });

    /* ── API CROSS-VALIDATE ──────────────────────────── */
    await test.step('Verify: API confirms order status = PAID', async () => {
      const updated = await (await orderService.getById(orderId)).json();
      expect(updated.status).toBe('PAID');
      expect(updated.paidAt).toBeDefined();
    });

    /* ── CLEANUP via API ─────────────────────────────── */
    await orderService.cancel(orderId);
  });
});
12
12
πŸ§ͺ

Tests Must Be Self-Contained

Every test creates its own data, validates it, and deletes it. Never depend on data from another test. Use afterEach cleanup tracking arrays.

πŸ”€

API for Setup, UI for Verification

If it's not what the test is testing, do it via API. The test goal determines which layer handles which step.

πŸ”

One storageState per Role

Create admin.json, user.json, viewer.json in globalSetup. Never hardcode credentials in test files β€” use env vars + fixtures.

🎯

Use data-testid Selectors

Never use CSS classes or XPath for production test selectors. data-testid survives redesigns. Make it a frontend team requirement.

⚑

Promise.all for Parallel API Calls

When creating multiple independent resources in setup, use Promise.all() β€” 3x–5x faster than sequential awaits.

🚫

Zero Hard Waits

Ban waitForTimeout from your codebase. Use Playwright's built-in auto-waits, waitForResponse, waitForURL, or element visibility assertions.

🏭

Factory Functions for All Test Data

buildUser(overrides) with faker-generated defaults. Overrides only what the test cares about. Zero hardcoded test data.

πŸ“¦

Service Layer = 1-File Endpoint Changes

When an API endpoint changes, update UserService.js β€” not 50 test files. This is the #1 maintainability win at scale.

πŸ“Š

test.step() for Readable Reports

Wrap logical sections in await test.step('...', async () => {}). HTML reporter shows nested steps β€” team can debug without reading code.

🏷️

Tag Every Test

@smoke, @critical, @regression tags in test titles. CI runs --grep @smoke on PR, full suite nightly. Selective execution = faster feedback.

πŸ”’

Security Test Layer Built-in

Test: no token β†’ 401, wrong role β†’ 403, other user's data β†’ 403/404, expired token β†’ 401. These come free with hybrid testing.

🧠

API as Test Oracle

After every UI write action (create, delete, update), cross-validate via API. API is the source of truth β€” UI is just a presentation layer.

⚑ Quick Decision: API vs UI β€” When to Use What
ActionUse API βœ…Use UI βœ…Reason
AuthenticationstorageState (globalSetup)Only for testing login flow itselfSave 5s per test
Test data creationAlways❌ Never for setup10–100x faster, more reliable
Data validationSchema + cross-checkVisual rendering + formatBoth! Use together
Cleanup/teardownAlways via DELETE❌ NeverReliable, fast, no UI dependency
Navigation to tested featureDirect URL with ID from APIOnly if testing the nav itselfSkip irrelevant UI flow
Form submissionIf testing API contractIf testing UX/validationDepends on test goal
File uploadsmultipart POST via APIIf testing drag-drop UXAPI upload is always faster
Post-action verificationCross-validate final stateVisual + toast messagesBoth give confidence