Skip to main content

Hybrid tests: API setup, UI check

Why This Matters

A UI test should spend its time on the behaviour it is about. If a test checks how the cart displays three products, adding those three products through three product cards is not the point; it is slow setup that can fail on its own. Prepare the data through the API, and use the browser only for what the user actually does and sees.

Sharing a sandbox between browser and API

The shop and its API share the same data. The browser gets a sandbox through its shop_session cookie, and the shop page shows its id:

Your sandbox id: 9c991daa-… Send it as X-Session-Id to see this cart and these orders from your API tests.

So a test can read that id from the page and send it with its API calls. Both then work on the same cart.

The test

From tests/module-4/hybrid.spec.ts:

test("a cart filled through the API shows up in the shop", async ({ page, request }) => {
  // The first visit creates the browser's sandbox (the shop_session cookie). Reload once,
  // so every request from here on uses that one cookie and the page shows its id.
  await page.goto("/shopping");
  const sandboxIdLabel = page.getByTestId("sandbox-id");
  await expect(sandboxIdLabel).toHaveText(/^[\w-]{8,}$/);
  await page.reload();
  // The page shows "…" until it knows the id: wait for the real value before reading it.
  await expect(sandboxIdLabel).toHaveText(/^[\w-]{8,}$/);
  const sandboxId = (await sandboxIdLabel.textContent())!.trim();

  // Three products in one go, without clicking through the UI.
  for (const productId of [5, 9, 10]) {
    const response = await request.post("/api/shop/cart/items", {
      headers: { "X-Session-Id": sandboxId },
      data: { productId },
    });
    expect(response.status()).toBe(201);
  }

  await page.reload();
  await expect(page.getByTestId("cart-button")).toContainText("3 items");

  await page.getByTestId("cart-button").click();
  const checkout = page.getByTestId("checkout-modal");
  for (const productId of [5, 9, 10]) {
    await expect(checkout.getByTestId(`cart-item-${productId}`)).toBeVisible();
  }
});

Three details:

  • The API calls check their own status. If the setup fails, the test fails at the setup with a clear message, not three steps later with a confusing one.
  • page.reload() at the end makes the shop fetch the cart again. A real user who changed the cart in another tab would see the same thing.
  • The first part looks more careful than it needs to be. It is, because the first version of this test failed in CI.

What CI found

The first version simply read the id straight after goto:

await page.goto("/shopping");
const sandboxId = (await page.getByTestId("sandbox-id").textContent())?.trim();
expect(sandboxId).toMatch(/^[\w-]{8,}$/);

It passed on a fast laptop, every time. In GitHub Actions it failed in all three browsers:

Error: expect(received).toMatch(expected)

Expected pattern: /^[\w-]{8,}$/
Received string:  "…"

The page shows a placeholder, …, until it knows the sandbox id. On the slower CI machine the test read it before the real id arrived: the same “value read too early” bug as in lesson 15, in a line that looked harmless because it was not an assertion. The rule is the same too: if the page might still be changing, wait with a web-first assertion (toHaveText(/…/)) first, and read the value only after that.

One retry in Firefox got past that line and then failed differently: after the reload, the cart was empty. The id the page showed and the sandbox the browser used afterwards were not the same. On a first visit the shop page sends several API requests at once, none of them with a cookie yet, so the server can start more than one sandbox. Reloading once, after the first visit, makes every later request carry the same shop_session cookie. A test that only ever ran locally would never have shown this; CI on a different machine did.

In the real run on a laptop this test took 2.9 seconds, about the same as a test that adds one product through the UI.

Clean up, or start clean

Each new browser context gets a new sandbox, so this test leaves nothing behind for others. On an application without sandboxes, delete what you created at the end of the test, or better, in a fixture (module 7), so it also happens when the test fails.

Exercise

Write a hybrid test the other way round: add the Webcam through the UI, then check through the API (with the browser’s sandbox id) that the cart contains exactly that product with quantity 1.

Show suggested solution
test("a product added in the UI is in the API's cart", async ({ page, request }) => {
  await page.goto("/shopping");
  await expect(page.getByTestId("sandbox-id")).toHaveText(/^[\w-]{8,}$/);
  await page.reload();
  await expect(page.getByTestId("sandbox-id")).toHaveText(/^[\w-]{8,}$/);
  const sandboxId = (await page.getByTestId("sandbox-id").textContent())!.trim();

  await page.getByRole("textbox", { name: "Search for items" }).fill("webcam");
  await page.getByTestId(/^product-\d+$/).filter({ hasText: "Webcam" })
    .getByRole("button", { name: "Add to Cart" }).click();
  await expect(page.getByTestId("cart-button")).toContainText("1 items");

  const cart = CartSchema.parse(
    await (await request.get("/api/shop/cart", { headers: { "X-Session-Id": sandboxId } })).json(),
  );
  expect(cart.items).toEqual([expect.objectContaining({ name: "Webcam", quantity: 1 })]);
});

Wait for the cart button to show “1 items” before calling the API; otherwise the API might be asked before the click’s request has finished.