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

Asserting Status, Headers and JSON

On this page
  1. Status codes: toBeOK and its limits
  2. Typing the JSON
  3. Asserting on the body
  4. Headers
  5. Make failures explain themselves

An API test is only as good as its assertions. "The request did not throw" proves little; "the search returned only matching products, each with a price" proves the feature works. This chapter covers the assertions that matter, how to type the JSON you get back, and how to make a failure tell you what went wrong without rerunning anything.

Status codes: toBeOK and its limits#

Playwright adds one API-specific matcher to expect: toBeOK(), which passes for any status from 200 to 299. When it fails, the error includes the full request and response log:

Error: expect(response).toBeOK() failed

Call log:
→ GET https://api.practicesoftwaretesting.com/products/does-not-exist
  user-agent: Playwright/1.65.0 (arm64; macOS 26.4) node/22.18
  accept: application/json
  accept-encoding: gzip,deflate,br
← 404 Not Found

That log is the reason to prefer it over expect(response.ok()).toBe(true), which fails with an unhelpful "expected true, received false". Notice the accept: application/json line: that is the extraHTTPHeaders from the project config at work.

toBeOK() is deliberately loose, though. When the exact status matters, assert it: a create endpoint that answers 200 instead of 201, or 204 where a client expects a body, is a real contract change.

expect(response.status()).toBe(201);

And remember the opposite case. By default Playwright does not throw on 4xx or 5xx responses: it hands you the response so you can test error handling. If you would rather have every unexpected error status fail loudly, pass failOnStatusCode: true to a request (or set it on a context you create). The error then contains the response body as well:

Error: apiRequestContext.get: 404 Not Found
Response text:
{"message":"Requested item not found"}

A teammate's test does await request.delete('/orders/42') and nothing else. The endpoint has been returning 500 for a week, yet the test is green. Why?

Unless you pass failOnStatusCode: true, a 500 is just a response object. A request with no assertion on it passes no matter what the server says.

Typing the JSON#

response.json() returns Promise<any>. That is convenient and dangerous: a typo in a field name compiles fine and fails at runtime, or worse, compares undefined to undefined and passes. Give the shape a name. Create lib/types.ts:

export type Product = {
  id: string;
  name: string;
  price: number;
  in_stock: boolean;
  category: { id: string; name: string; slug: string };
  brand: { id: string; name: string };
};

export type Page<T> = {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  data: T[];
};

Annotating the result of json() with these types gives you autocompletion and catches typos at compile time. It does not check anything at runtime: TypeScript believes you. Chapter 5 replaces these hand-written types with a schema that checks the data and produces the type at the same time.

Asserting on the body#

Create tests/api/products.spec.ts:

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

test('search returns only matching products', async ({ request }) => {
  const response = await request.get('/products/search', {
    params: { q: 'pliers' },
  });

  await expect(response).toBeOK();
  expect(response.headers()['content-type']).toContain('application/json');

  const body: Page<Product> = await response.json();
  expect(body.total).toBe(body.data.length);
  for (const product of body.data) {
    expect(product.name.toLowerCase()).toContain('pliers');
    expect(product.price).toBeGreaterThan(0);
  }
});

test('first page has the shape the shop relies on', async ({ request }) => {
  const response = await request.get('/products', { params: { page: 1 } });
  const body: Page<Product> = await response.json();

  expect(body).toMatchObject({ current_page: 1, per_page: 9 });
  expect(body.data[0]).toEqual(
    expect.objectContaining({
      id: expect.any(String),
      name: expect.any(String),
      price: expect.any(Number),
      category: expect.objectContaining({ slug: expect.any(String) }),
    }),
  );
});

test('unknown product is a 404 with a message', async ({ request }) => {
  const response = await request.get('/products/does-not-exist');

  expect(response.status()).toBe(404);
  expect(await response.json()).toEqual({ message: 'Requested item not found' });
});

test('failOnStatusCode turns a 404 into an exception', async ({ request }) => {
  await expect(
    request.get('/products/does-not-exist', { failOnStatusCode: true }),
  ).rejects.toThrow(/404/);
});
Running 4 tests using 4 workers

  ✓  2 [api] › tests/api/products.spec.ts:35:1 › unknown product is a 404 with a message (179ms)
  ✓  3 [api] › tests/api/products.spec.ts:42:1 › failOnStatusCode turns a 404 into an exception (179ms)
  ✓  1 [api] › tests/api/products.spec.ts:4:1 › search returns only matching products (184ms)
  ✓  4 [api] › tests/api/products.spec.ts:20:1 › first page has the shape the shop relies on (206ms)

  4 passed (639ms)

The matchers worth knowing, and when each one fits:

  • toEqual compares the whole value recursively. Use it for small, fully known bodies such as the error message above. On a large body it is brittle: any new field the API adds breaks the test, even though no client cares.
  • toMatchObject checks only the properties you list and ignores the rest. Good for "the page metadata says page 1, nine per page".
  • expect.objectContaining, expect.any(Number), expect.stringMatching(/.../) describe a shape instead of exact values. They are the right tool for data you do not control, like ids and generated timestamps, which change between runs.
  • Loops with plain assertions, as in the search test, express rules that must hold for every item. They are the assertions most likely to catch a real bug: here, a search that starts returning unrelated products.

The search test also checks total against the number of items. That kind of internal consistency check is cheap and catches pagination bugs that a "status is 200" test never would.

A test asserts expect(await res.json()).toEqual({ id: 7, name: 'Saw', price: 9.99 }). The backend team adds a created_at field and the test fails, although no client is affected. What is the better assertion?

toMatchObject checks the fields you care about and tolerates additions, which are backwards compatible. A hard-coded timestamp would break tomorrow, and stringify comparison is even stricter than toEqual.

Headers#

response.headers() returns an object with lower-case header names, so headers()['content-type'] works whatever case the server used. Assert on headers that clients depend on: content-type (a JSON API that suddenly returns text/html usually means an error page from a proxy), caching headers on endpoints a CDN caches, location after a create, and security headers such as CORS rules if a browser front end calls the API.

Use toContain rather than toBe for content-type, because servers legitimately append a charset (application/json; charset=utf-8).

Make failures explain themselves#

When an assertion deep in a loop fails, "expected 0 to be greater than 0" is not much to go on. Every expect accepts a custom message as its second argument, and it is worth adding when the default output would not tell you which item or request was wrong:

expect(response.status(), await response.text()).toBe(201);

Passing the response text as the message means a failed create shows the server's validation errors right in the report. The fixtures in chapter 3 use exactly this line.

For the full request and response of a failing test, turn on tracing. The trace viewer shows API calls made through any request context with their headers and bodies, just like browser network requests; chapter 5 of the Playwright course shows how to open it.

You annotate const body: Product = await response.json(). The API renames price to unit_price. What happens?

A type annotation is a promise you make to the compiler, not a runtime check. json() returns whatever the server sent. Chapter 5 adds a schema that does check it.

Next: every useful API has endpoints that need a logged-in user. Chapter 3 gets a token and shares it between API calls and the browser.