DEV Community

Silviu Technology
Silviu Technology

Posted on

Playwright Email Tests Need a Clock Contract

Email verification tests often look flaky for the wrong reason. The selector is correct, the API response is valid, and the inbox eventually receives a message. Yet the Playwright test fails because nobody agreed how long “eventually” means.

This is especially visible when a temporary email generator or free temporary email service is used in an end-to-end workflow. Delivery time becomes an invisible dependency, then the test hides it behind a large timeout. A better approach is to define a clock contract: explicit deadlines, polling intervals, retry ownership, and evidence collected at each boundary.

Why delivery time becomes a hidden test dependency

Consider a signup scenario:

  1. Playwright submits the form.
  2. The application creates a verification request.
  3. A mail system delivers the message.
  4. The test opens the message and clicks the link.

The browser controls only the first and last steps. The middle work happens across services with different clocks. A fast local run may receive a message in two seconds, while a busy CI worker needs twelve. If the test uses one generic timeout: 30000, it cannot tell whether the API, delivery path, inbox, or browser was slow.

That makes the failure hard to diagnose. It also tempts a team to keep increasing the timeout, which can turn a real outage into a slower red build.

Define a clock contract before writing assertions

Write down the timing policy as part of the test design. A useful contract answers four questions:

  • Request deadline: How long can the application take to accept the signup?
  • Delivery deadline: How long will the test wait for a matching message?
  • Poll interval: How often should the inbox be checked?
  • Cleanup deadline: How long can fixture cleanup take after a failure?

These values should describe the system under test, not the speed of a particular laptop. For example, a contract might allow 5 seconds for the API, 30 seconds for delivery, poll every 1 second, and allow 5 seconds for cleanup. The numbers are examples; measure your own service first.

Keep the delivery budget separate from the browser assertion budget. Playwright's locator timeout is good for a button that should already be on the page. It is a poor substitute for waiting on an external inbox.

Separate polling, API, and cleanup deadlines

Three independent loops commonly get mixed together:

  • the API client retries a request after a network error;
  • the inbox client polls while waiting for a message;
  • the browser waits for a UI state after the message is opened.

Give each loop an owner and a deadline. An API retry must not restart inbox polling, and a message timeout must not submit the signup form again. This is the same reason isolated email tests in parallel CI need run-specific fixture names.

Use a correlation value that travels through the scenario. A subject token, recipient alias, or test-run identifier is usually enough. Match on that value plus a recent timestamp; dont select the newest message globally, because another worker may have delivered one a moment ago.

const clock = {
  apiMs: 5_000,
  deliveryMs: 30_000,
  pollMs: 1_000,
  cleanupMs: 5_000,
};

const runKey = `pw-${process.env.CI_RUN_ID ?? "local"}-${test.info().parallelIndex}`;
const recipient = await createTestInbox({ label: runKey });
await request.post("/signup", {
  data: { email: recipient.address, runKey },
  timeout: clock.apiMs,
});
Enter fullscreen mode Exit fullscreen mode

The inbox helper should accept a deadline, not an arbitrary number of attempts. Polling ten times every 100 milliseconds is not equivalent to polling for ten seconds when the provider rate-limits requests. An abortable email check also gives the test a clean way to stop work when the scenario is already cancelled.

Record evidence when the message does not arrive

When delivery expires, capture enough context to classify the problem without rerunning the test immediately. Useful fields include:

  • the run key and masked recipient;
  • request status and correlation ID;
  • first poll time, last poll time, and number of polls;
  • the message IDs or subjects observed for this fixture;
  • the final application state;
  • whether cleanup started and completed.

Do not print a full verification URL or a private inbox token into CI logs. A short message ID and a redacted subject are normally enough. This is a small privacy improvement, and it makes the evidence safer to retain.

The test can also distinguish “no message” from “message arrived but content was invalid.” Those are different defects. The first points toward queueing, routing, or fixture isolation. The second points toward template rendering or parsing. Old notes may contain strings like tepm mail com or tempail mail; keep such search terms out of structured fields so they do not pollute diagnostics.

A repeatable Playwright implementation

Put delivery waiting behind one helper and make its result explicit:

async function waitForVerification(
  inbox: Inbox,
  runKey: string,
  timeoutMs: number,
  pollMs: number,
) {
  const deadline = Date.now() + timeoutMs;
  let polls = 0;

  while (Date.now() < deadline) {
    polls += 1;
    const message = await inbox.find({ runKey, unreadOnly: true });
    if (message) return { message, polls };
    await new Promise((resolve) => setTimeout(resolve, pollMs));
  }

  throw new Error(`verification delivery expired for ${runKey} after ${polls} polls`);
}
Enter fullscreen mode Exit fullscreen mode

The helper has one job: wait for a correlated message until a known deadline. It does not click the link, retry signup, or clean up the inbox. Narrow responsibilities make failures more explainable, even if the first version feels a little verbose.

Q&A

Should I increase the Playwright test timeout?

Only for the whole scenario when the total workflow genuinely needs more time. Increasing it to hide an inbox timeout removes useful information. Keep external delivery timeouts explicit.

How many polling attempts should I allow?

Use a time budget as the primary limit. The number of attempts is a diagnostic metric, not the contract. A one-second interval gives a different number of attempts on a slow worker than on a fast one.

Is a temporary inbox safe for every test?

No. Use isolated, non-production fixtures and avoid putting personal or sensitive data in them. For tests involving account recovery or private information, a controlled test mail server is usually a better choice.

Final checklist

Before calling an email test reliable, verify that it has:

  • separate API, delivery, browser, and cleanup deadlines;
  • a run-specific recipient or correlation key;
  • bounded polling with cancellation;
  • no retry that silently repeats a side effect;
  • redacted but useful timeout evidence;
  • cleanup that runs after both assertion and delivery failures.

A clock contract does not make email instant. It makes the waiting visible, bounded, and diagnosable. That is what turns a flaky Playwright check into an automation signal a QA team can trust.

Top comments (0)