Asserting responses and schemas
Why This Matters
A status code says very little. An API can return 200 with an empty list, a price as a string, or a field renamed in last week’s release, and a test that only checks the status stays green. Check the shape of every response, then the values that matter.
Status, headers, body
const response = await api.get("products/5");
expect(response.status()).toBe(200); // or: expect(response.ok()).toBeTruthy()
expect(response.headers()["x-session-id"]).toBe(sandboxId);
const product = await response.json();
expect(product).toMatchObject({ id: 5, name: "Bluetooth Headphones", price: 59.99 });
toMatchObject checks the fields you list and ignores the rest. Use it for the values that matter to this test.
From “as” to a real check
Module 1 typed responses with as, which only tells TypeScript what you hope comes back. A schema checks it at runtime. The repository uses zod; src/schemas.ts describes every response of the Shop API:
export const CartItemSchema = z.strictObject({
productId: z.number().int(),
sku: z.string(),
name: z.string(),
image: z.string(),
price: z.number(),
quantity: z.number().int().min(1),
lineTotal: z.number(),
});
CartItemSchema.parse(body) returns typed data when the body matches, and throws a precise error when it does not: which field, what was expected, what came instead. strictObject also rejects fields that are not in the schema, matching the API’s own additionalProperties: false.
The cart, checked properly
test("adding a product returns the whole cart, with 21% tax", async ({ api }) => {
const response = await api.post("cart/items", { data: { productId: 5, quantity: 2 } });
expect(response.status()).toBe(201);
const cart = CartSchema.parse(await response.json());
expect(cart.items).toEqual([expect.objectContaining({ productId: 5, quantity: 2, lineTotal: 119.98 })]);
expect(cart.subtotal).toBe(119.98);
expect(cart.tax).toBe(toCents(119.98 * TAX_RATE));
expect(cart.total).toBe(toCents(cart.subtotal + cart.shipping + cart.tax));
});
The tax is not typed in by hand: it reuses TAX_RATE and toCents() from module 1. The real API returns a tax of 25.2 and a total of 145.18 for this cart.
Test the unhappy paths
Every error from the Shop API has the same shape, { "error": { "code", "message", "details"? } }. These are real responses:
{ "error": { "code": "OUT_OF_STOCK", "message": "HD Monitor is out of stock." } }
{ "error": { "code": "INSUFFICIENT_STOCK", "message": "Only 20 of Bluetooth Headphones left in stock.",
"details": [{ "field": "quantity", "message": "Must be at most 20." }] } }
{ "error": { "code": "VALIDATION_ERROR", "message": "The order could not be placed. Check the fields.",
"details": [{ "field": "billing.email", "message": "Email is required." },
{ "field": "billing.city", "message": "City is required." }] } }
So one schema covers them all, and the tests assert on the stable code, not on the wording of message:
test("an out-of-stock product cannot be added", async ({ api }) => {
const response = await api.post("cart/items", { data: { productId: 3 } });
expect(response.status()).toBe(409);
expect(ErrorSchema.parse(await response.json()).error.code).toBe("OUT_OF_STOCK");
});
Exercise
Write a test that places an order and checks that the product’s stock went down by the quantity ordered. Use PayPal as the payment method; it needs no card details. The billing fields are in the API documentation’s example.
Show suggested solution
The complete version is checkout turns the cart into an order and lowers the stock in tests/module-4/orders.api.spec.ts. The core of it:
const before = await stockOf(api, 5);
await api.post("cart/items", { data: { productId: 5, quantity: 2 } });
const response = await api.post("orders", { data: order });
expect(response.status()).toBe(201);
expect(OrderSchema.parse(await response.json()).status).toBe("paid");
expect(await stockOf(api, 5)).toBe(before - 2);
Reading the stock before the order keeps the test correct even if the starting stock changes. Because every test has its own sandbox, no other test can change the stock in between.