Exit course
Chapter 5 of 9 Intermediate 8 min read 3 quick checks Updated

Test Data Setup and Teardown Through the API

On this page
  1. A small helper for lookups
  2. The fixture: create, hand over, clean up
  3. Why the fixture shape matters
  4. Asserting on the server after a UI action
  5. Habits that keep API-built data reliable

Most UI tests are not about creating data, yet many of them start by clicking through the screens that create it. A test of "remove a favorite" first searches for a product, opens it, clicks "Add to favourites", navigates to the favorites page, and only then gets to the part it is about. Every one of those steps is time, and every one is a place the test can fail for an unrelated reason.

The fix is the most valuable thing in this course: arrange through the API, act and assert in the UI, clean up through the API. This chapter builds it as a fixture.

A small helper for lookups#

Tests should not hard-code database ids. Look things up by something stable and human-readable instead. Create lib/shop.ts:

import { expect, type APIRequestContext } from '@playwright/test';
import type { Page, Product } from './types';

export async function findProduct(api: APIRequestContext, name: string): Promise<Product> {
  const response = await api.get('/products/search', { params: { q: name } });
  await expect(response).toBeOK();
  const { data }: Page<Product> = await response.json();
  const product = data.find((p) => p.name === name);
  if (!product) throw new Error(`No product named ${name}`);
  return product;
}

The helper takes any APIRequestContext, so it works with the logged-in api fixture, with request, or with a context you create. The explicit error message matters: "No product named Bolt Cutters" points at test data that changed, while a TypeError on undefined.id three lines later points nowhere.

The fixture: create, hand over, clean up#

Create tests/ui/favorites.spec.ts:

import { uiTest as base, expect } from '../fixtures';
import { findProduct } from '../../lib/shop';
import type { Product } from '../../lib/types';

type Favorite = { id: string; product: Product };

const test = base.extend<{ favorite: Favorite }>({
  // Arrange through the API, clean up through the API.
  favorite: async ({ api }, use) => {
    const product = await findProduct(api, 'Bolt Cutters');
    const response = await api.post('/favorites', { data: { product_id: product.id } });
    expect(response.status()).toBe(201);
    const { id } = await response.json();

    await use({ id, product });

    // 204 if it still existed, 404 if the test already removed it
    const cleanup = await api.delete(`/favorites/${id}`);
    expect([204, 404]).toContain(cleanup.status());
  },
});

test('a favorite created through the API is listed', async ({ page, favorite }) => {
  await page.goto('/account/favorites');

  const card = page.getByTestId(`favorite-${favorite.id}`);
  await expect(card.getByTestId('product-name')).toHaveText(favorite.product.name);
});

test('removing a favorite in the UI removes it on the server', async ({ page, api, favorite }) => {
  await page.goto('/account/favorites');
  await page.getByTestId(`favorite-${favorite.id}`).getByTestId('delete').click();
  await expect(page.getByTestId(`favorite-${favorite.id}`)).toHaveCount(0);

  await expect.poll(async () => (await api.get('/favorites')).json()).toEqual([]);
});
npx playwright test --project=chromium --project=firefox tests/ui/favorites.spec.ts
Running 4 tests using 4 workers

  ✓  4 [chromium] › tests/ui/favorites.spec.ts:23:1 › a favorite created through the API is listed (2.5s)
  ✓  2 [chromium] › tests/ui/favorites.spec.ts:30:1 › removing a favorite in the UI removes it on the server (2.9s)
  ✓  3 [firefox] › tests/ui/favorites.spec.ts:23:1 › a favorite created through the API is listed (2.5s)
  ✓  1 [firefox] › tests/ui/favorites.spec.ts:30:1 › removing a favorite in the UI removes it on the server (3.3s)

  4 passed (5.8s)

Follow the fixture chain for one test: favorite needs api, which needs token, which needs the worker's account. uiTest also gives the page a storageState with the same token. So before the first line of the test body runs, the worker has a customer, the customer is logged in on both the API client and the browser, and the favorite exists. The test itself is three lines about what it actually tests.

Why the fixture shape matters#

Teardown after use() runs even when the test fails. That is the main reason to put setup in a fixture rather than at the top of the test: a test that fails halfway through still cleans up after itself, so one failure does not leave data behind that breaks the next run.

The teardown tolerates the expected states. The second test deletes the favorite itself, so the cleanup sees 404; the first test leaves it, so cleanup sees 204. Accepting exactly those two, and nothing else, keeps the cleanup honest: a 500 from the delete endpoint still fails the test, instead of being silently ignored by a cleanup wrapped in try/catch.

Only tests that ask for favorite pay for it. Fixtures are lazy. A test in the same file that does not list favorite never creates one.

The data belongs to this worker. The favorite is created on the worker's own account, so the second test can assert that the whole list is empty. On a shared account, the strongest safe assertion would be "the list no longer contains this id".

A test creates an order through the API in its first line and deletes it in its last line. When an assertion in the middle fails, orders pile up in the test environment. What is the clean fix?

Fixture teardown runs whether the test passed or failed, and the setup lives in one place. try/finally works but has to be repeated in every test, and deleting everything in beforeAll breaks other workers that are using their data at that moment.

Asserting on the server after a UI action#

The second test checks both sides. The UI assertion (toHaveCount(0)) shows that the card disappeared. But a front end can remove a card optimistically and then fail to save; the page looks right while the server still has the favorite. Asking the API closes that gap.

The UI may update before the server has finished, so do not assert on a single API call right after the click. expect.poll calls the function repeatedly until the matcher passes or the timeout runs out, which gives you the same retrying behaviour that web-first assertions give you for the page:

await expect.poll(async () => (await api.get('/favorites')).json()).toEqual([]);

Use the same pattern for anything eventually consistent: a search index, a background job, an email that a webhook should have triggered.

After clicking "Save" in the UI, a test calls api.get('/settings') once and asserts the new value. It fails now and then, although the setting is always saved. What is the best fix?

The save is asynchronous, so a single read can come too early. expect.poll retries the read until it matches or times out, without the fixed delay that slows every run and still fails on a slow day.

Habits that keep API-built data reliable#

  • Create what you need, per test. Data created in beforeAll is shared by every test in the worker and changed by them in turn. A test-scoped fixture gives each test a known starting point.
  • Make names unique when the API requires unique values (emails, usernames, SKUs). The account fixture builds its email from a timestamp and the worker index for that reason.
  • Do not assert global totals. "The shop has 50 products" breaks as soon as anyone adds one. Assert on the records your test created.
  • Keep one end-to-end path through the UI. If customers can add favorites from the product page, one test should still do exactly that. API setup is for tests whose subject is something else.
  • Clean up in the same layer you created in. Data created through the API is deleted through the API, not through the UI.

Your team replaced every "add to favorites" click in setup with an API call. Which test should still click the real button?

The API shortcut skips the UI on purpose, so it cannot detect a broken button. The feature itself still needs one test that goes through the UI; every other test can use the shortcut.

Your UI tests now get their data in milliseconds. The next chapter checks that the data the API returns has the shape your code expects.