Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 35 ยท Projects

Project: Combine API Setup with UI Checks

Build a fast, reliable suite: create test data through an API, verify it in the browser, clean up afterwards, and share setup with fixtures.

The slowest, flakiest part of most browser suites is setup. A test that wants to check how a project with three finished tasks looks should not spend forty seconds clicking through sign-up, "New project" and "Add task" forms first. Those forms are not what the test is about, and every extra click is another chance to fail for an unrelated reason.

The fix is a pattern with three steps: seed the data through an API, verify it in the user interface, and clean up afterwards. In this project you will build all three, hide them behind a fixture, and design a suite that stays fast as it grows. Page Objects and Better Test Structure introduced the idea of app actions; here you put it to work.

Cypress and Playwright cannot run on this site, so their code is read-only. The runnable examples are Node.js stand-ins on the server-side runner: a small HTTP API on the loopback address, a test runner with fixtures, and a "page" that is server-rendered HTML, which the stand-in test reads with a simple pattern match where a real browser test would use a locator. The API calls and the fixture mechanics are real; the browser is the stand-in.

The shape of a good test

Here is the idea in one picture. The test talks to the API for everything that is not under test, and to the browser only for what is.

sequenceDiagram
  participant T as Test
  participant A as API
  participant B as Browser
  T->>A: POST /api/projects (seed)
  A-->>T: id and data
  T->>B: open /projects/id
  B-->>T: rendered page
  T->>T: assert on what the user sees
  T->>A: DELETE /api/projects/id (cleanup)

Setup and cleanup go through the API; only the check goes through the browser.

Seed by API

Both tools can send HTTP requests without a page. In Playwright that is the request fixture, and in Cypress it is cy.request.

TypeScript
// Playwright (read-only)
import { test, expect } from '@playwright/test';

test('shows progress for a seeded project', async ({ page, request }) => {
  const created = await request.post('/api/projects', {
    data: { name: 'Launch plan' },
  });
  expect(created.status()).toBe(201);
  const project = await created.json();

  for (const title of ['Write copy', 'Book venue', 'Send invites']) {
    await request.post(`/api/projects/${project.id}/tasks`, { data: { title } });
  }

  await page.goto(`/projects/${project.id}`);
  await expect(page.getByTestId('task')).toHaveCount(3);
});
JavaScript
// Cypress (read-only)
it('shows progress for a seeded project', () => {
  cy.request('POST', '/api/projects', { name: 'Launch plan' }).then(({ status, body }) => {
    expect(status).to.eq(201)
    cy.request('POST', `/api/projects/${body.id}/tasks`, { title: 'Write copy' })
    cy.request('POST', `/api/projects/${body.id}/tasks`, { title: 'Book venue' })
    cy.visit(`/projects/${body.id}`)
    cy.get('[data-cy=task]').should('have.length', 2)
  })
})

Two details deserve attention. First, the test asserts the status of the setup call. If the seed fails and you skip that check, the page test fails later with a confusing "expected 3 tasks, found 0". Second, the test uses the id the server returned instead of a hard-coded one, so it works against any database.

Testing APIs Directly covers request and cy.request in detail, including headers and bodies.

A stand-in you can run

The stand-in below starts a real HTTP server on the loopback address inside the sandbox. It offers the same endpoints as the examples, plus GET /projects/:id, which returns HTML like a server-rendered page. A tiny helper reads data-testid attributes from that HTML. Then the test seeds a project over HTTP, checks the "page", and deletes the project.

Node.js Seed over HTTP, verify the page, clean up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line proves the cleanup worked: the page now answers 404. Notice the escaped title too. The browser shows Send <invites> as text because the server turned < into &lt;, which is exactly the kind of detail a UI check can catch.

Fixtures: setup and cleanup in one place

If every test repeats "create project, add tasks, remember to delete", the pattern is easy to get wrong. A fixture packages the setup and the teardown, and the runner guarantees the teardown runs even when the test fails. Playwright has this built in with test.extend:

TypeScript
// Playwright (read-only): fixtures.ts
import { test as base } from '@playwright/test';

type Project = { id: number; name: string };

export const test = base.extend<{ project: Project }>({
  project: async ({ request }, use, testInfo) => {
    // setup: a unique name keeps parallel workers apart
    const name = `Project ${testInfo.workerIndex}-${Date.now()}`;
    const res = await request.post('/api/projects', { data: { name } });
    const project = await res.json();

    await use(project); // the test runs here

    // teardown: runs even if the test failed
    await request.delete(`/api/projects/${project.id}`);
  },
});
export { expect } from '@playwright/test';

A test then asks for what it needs by name:

TypeScript
// Playwright (read-only)
import { test, expect } from './fixtures';

test('a new project starts empty', async ({ page, project }) => {
  await page.goto(`/projects/${project.id}`);
  await expect(page.getByTestId('progress')).toHaveText('0 of 0 done');
});

In Cypress you reach the same result with a custom command plus an afterEach that deletes what the test created. Keep the id in a variable that lives in the test file, and clean up through the API. Hooks, Fixtures and Custom Commands explains both mechanisms.

JavaScript
// Cypress (read-only)
let projectId

beforeEach(() => {
  cy.request('POST', '/api/projects', { name: `Project ${Date.now()}` })
    .its('body.id')
    .then((id) => { projectId = id })
})

afterEach(() => {
  if (projectId) cy.request('DELETE', `/api/projects/${projectId}`)
})

The stand-in below builds a miniature fixture runner. Fixtures are functions that receive use; the runner sets them up in order, runs the test, and then tears down in reverse, including after a failure.

Node.js A fixture runner that always cleans up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the event log. Every setup has a matching cleanup, the failing test included, and in the right order: tasks are removed before the project they belong to. The final line, projects left behind: 0, is the property you want from every real suite.

This runner is a simplified model. Playwright's real fixtures are also lazy (they run only for tests that name them), can be scoped to a worker, and can depend on other fixtures automatically.

Designing a fast suite

A few rules keep the suite fast as it grows.

  • Isolate data per test. Each test gets its own project, with a unique name. Tests that share a record break each other as soon as they run in parallel.
  • Seed through the API, verify through the UI. Spend browser time only on what a user sees.
  • Test the form once. One test fills in "New project" through the real interface. All other tests create projects by API.
  • Clean up through the API too. It is faster and more reliable than clicking Delete.
  • Assert setup results. Check status codes in the setup path so failures point at the real cause.
  • Don't reuse ids across runs. Use the ids the server returns.

Shared data is the classic cause of flaky parallel runs (see Finding and Fixing Flaky Tests). The stand-in below makes the problem visible. Two tests each add one task and then check "exactly one task". With a shared project they run side by side and both fail; with a project per test, both pass. A small barrier forces the overlap so the result is the same on every run.

Node.js Why shared data breaks parallel tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why seed test data through an API instead of the UI?

    Setup that goes through the interface adds time and extra failure points. An API call does the same job quickly and keeps the test focused.
  2. 2. What does a fixture's teardown guarantee in Playwright?

    Code after use() in a fixture runs once the test is finished, whether it passed or failed, so created data does not pile up.
  3. 3. A setup call returns status 500 but the test never checks it. What is the likely result?

    Asserting the setup status makes the failure point at the real cause instead of a missing element on the page.
  4. 4. Two parallel tests edit the same project and fail only sometimes. What is the best fix?

    Shared mutable data makes tests depend on each other's timing. Per-test data removes the dependency.
  5. 5. Which test should still go through the real 'New project' form?

    Seeding by API skips the form, so keep one test that exercises the form on purpose. The others can take the shortcut.

Summary

  • Seed data through the API, verify what the user sees in the browser, and clean up through the API.
  • Assert the status of setup calls and use ids returned by the server.
  • Fixtures package setup and teardown; teardown must run even when the test fails.
  • Give each test its own uniquely named data so tests can run in parallel.
  • Keep one real UI test for each form or flow, and let the rest take the API shortcut.
  • A good suite leaves nothing behind: check for leftover data on purpose.

Next: Exercises with Solutions