DEV Community

Silviu Technology
Silviu Technology

Posted on

Playwright Email Tests Need a Message Contract

Email-based end-to-end tests often fail with a misleading symptom: the browser completed signup, but the test cannot find the verification message. The team then increases the timeout and hopes the next run is green.

That approach treats an email as a blob that either exists or does not. A more reliable approach is to define a message contract. The contract describes what the application promises to send, how the test identifies the right message, and which evidence is needed when one stage fails.

This is especially useful when a disposable mail address or a throwaway email generator is used for isolated QA runs. A private inbox reduces cross-test contamination, but it does not tell you whether the failure happened during enqueueing, delivery, indexing, or link construction.

Why an email test needs a contract

An email verification flow crosses several systems:

  1. Playwright fills and submits the form.
  2. The application validates the address and creates a message job.
  3. A worker renders and sends the message.
  4. The mailbox provider receives and indexes it.
  5. The test finds the current message and follows its link.

If the test only asserts that a message eventually appears, it can pass for the wrong reason. A stale message might contain a valid-looking link. A shared inbox might return another test's email. A message can arrive with the right subject but the wrong recipient.

The setup are easier to reason about when the expected properties are explicit. For each test run, define at least these fields:

  • Recipient: the unique address or inbox assigned to the run.
  • Scenario ID: a value connecting the browser trace, application log, and message.
  • Message purpose: for example, signup-verification.
  • Freshness rule: a message must be created after the signup request.
  • Link rule: the URL must contain the current user or scenario identity.
  • Redaction rule: tokens and full message bodies never enter CI logs.

Define the message contract

Keep the contract separate from the polling mechanics. That separation makes failures specific instead of producing one generic timeout.

type EmailExpectation = {
  recipient: string;
  purpose: "signup-verification" | "password-reset";
  scenarioId: string;
  createdAfter: number;
  subjectIncludes: string;
};

type TestEmail = {
  id: string;
  to: string;
  subject: string;
  receivedAt: string;
  text: string;
};
Enter fullscreen mode Exit fullscreen mode

The createdAfter value is important. Without it, a successful query can return an old message and make the test become falsely green. The scenario ID is equally useful when several parallel jobs are using the same mail service.

Do not put a token into a selector or use the full verification URL as an assertion fixture. Assert the safe parts of the contract first: recipient, purpose, age, and correlation. Then extract the link and validate its destination with a narrowly scoped check.

For the privacy side of this design, a privacy boundary for email fixtures is a useful companion to the testing mechanics. The mailbox should be isolated enough that a test cannot accidentally read another user's message.

Implement a contract-aware Playwright fixture

The fixture should poll with a deadline and report which part of the contract was not met. It should not silently swallow provider errors or retry forever.

async function waitForContract(
  request: APIRequestContext,
  expected: EmailExpectation,
  timeoutMs = 45_000,
): Promise<TestEmail> {
  const deadline = Date.now() + timeoutMs;
  let lastCount = 0;

  while (Date.now() < deadline) {
    const response = await request.get(
      `/test-inbox?to=${encodeURIComponent(expected.recipient)}`,
    );
    if (!response.ok()) {
      throw new Error(`Inbox lookup failed with ${response.status()}`);
    }

    const messages = (await response.json()) as TestEmail[];
    lastCount = messages.length;
    const match = messages.find((message) => {
      const receivedAt = Date.parse(message.receivedAt);
      return message.to === expected.recipient
        && message.subject.includes(expected.subjectIncludes)
        && receivedAt >= expected.createdAfter;
    });

    if (match) return match;
    await new Promise((resolve) => setTimeout(resolve, 1_000));
  }

  throw new Error(
    `Email contract timed out for ${expected.purpose}; `
      + `scenario=${expected.scenarioId}; messages=${lastCount}`,
  );
}
Enter fullscreen mode Exit fullscreen mode

The code keeps the query bounded and includes a small amount of useful evidence. In a real project, also record whether the application acknowledged the enqueue request. The test should start mailbox polling only after that acknowledgement, otherwise a slow UI request and a slow mail provider become one confusing wait.

Diagnose failures by contract stage

When a run fails, classify it before changing timeouts:

  • No application acknowledgement: inspect the form submission, API response, or transaction.
  • Acknowledged but no message: inspect the worker, provider response, and sender queue.
  • Message exists but is not returned: inspect recipient filtering, indexing delay, or the test-inbox adapter.
  • Wrong or stale message: inspect the freshness rule and scenario correlation.
  • Correct message but bad link: inspect URL construction and the application environment.

This classification also helps decide what to capture. A message ID and scenario ID are often enough; logging more informations can expose verification tokens. If a provider returns a dummy e mail label during fixture setup or a developer searches for tem email in notes, keep those phrases as plain text only. They should never become a selector, primary keyword, or message identity.

The scenario IDs for signup email tests show the same idea from another angle: the test needs a stable way to connect the browser action to the expected inbox event.

A repeatable CI checklist

Before merging an email-driven Playwright test, verify that:

  • Each run receives a unique address, inbox, or scenario partition.
  • The test asserts application acknowledgement before polling.
  • The message contract checks recipient, purpose, freshness, and correlation.
  • Polling has a deadline and a useful last-observation error.
  • Provider failures are distinguished from an empty inbox.
  • Tokens and message bodies are redacted from traces and logs.
  • Retries create a new scenario ID instead of reusing the previous one.

If the checks are slow, measure each stage before changing the timeout. Sometimes the inbox index is the bottleneck; sometimes the application never queued anything. A little measurement makes the fix easierer to choose.

Questions teams usually ask

How long should the polling deadline be?

Use the normal delivery percentile for the environment plus a modest margin, then keep the deadline finite. The right number depends on your provider and CI region, so measure it rather than copying a timeout from another project.

Is a message contract overkill for one test?

For one test, a small expectation object is enough. The value appears when the flow is retried, parallelized, or maintained by someone who did not write the original fixture.

Reliable email tests are not created by waiting longer. They are created by making the expected message observable, bounded, and specific enough that a failure points to the next investigation.

Top comments (0)