// β 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}`);
});
| Concern | Pure UI | Pure API | API + UI Hybrid β |
|---|---|---|---|
| Speed | Slow (5β30s/test) | Fast (<1s) | Fast (2β5s/test) |
| Test Data Setup | Fragile, slow | Reliable, fast | API-seeded β |
| UI Rendering Check | Yes | No | Yes (focused) |
| Auth Setup | Repeat login every test | Token injection | storageState reuse |
| Flakiness Risk | High (UI timing) | Very low | Low (minimal UI) |
| Cleanup | Often skipped | Easy via DELETE | API cleanup in afterEach |
// 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
// 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 };
// 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}`);
});
// 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');
});
// 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')}`);
});
// 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',
});
// 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();
},
// 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
});
// 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);
});
// 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);
});
});
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
});
// 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
}
});
// 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);
});
// β 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
// 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
// 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
});
// 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
// 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);
});
// 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
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
// 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();
}
}
// 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);
}
}
// 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);
});
});
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.
| Action | Use API β | Use UI β | Reason |
|---|---|---|---|
| Authentication | storageState (globalSetup) | Only for testing login flow itself | Save 5s per test |
| Test data creation | Always | β Never for setup | 10β100x faster, more reliable |
| Data validation | Schema + cross-check | Visual rendering + format | Both! Use together |
| Cleanup/teardown | Always via DELETE | β Never | Reliable, fast, no UI dependency |
| Navigation to tested feature | Direct URL with ID from API | Only if testing the nav itself | Skip irrelevant UI flow |
| Form submission | If testing API contract | If testing UX/validation | Depends on test goal |
| File uploads | multipart POST via API | If testing drag-drop UX | API upload is always faster |
| Post-action verification | Cross-validate final state | Visual + toast messages | Both give confidence |