DEV Community

ryanlee
ryanlee

Posted on

TypeScript Contracts for React Email Tests

Email tests become confusing when the UI, the test runner, and the delivery provider all speak different languages. A React component waits for a verification state, while a Node.js service waits for a message, and the test waits for both. When something is slow, the failure usually says only that a button never changed.

The fix I like is a small TypeScript contract between the application and its mail test adapter. It makes the boundary explicit, gives every scenario a stable identity, and lets the same React test move from a fast fake transport to a real disposable mail address when the delivery path needs coverage.

The boundary is the product of the test

An email test is not just an assertion about a message. It is a short workflow:

  1. Create a scenario with a unique ID.
  2. Submit an address through the React form.
  3. Wait for the backend to send a message.
  4. Read the message and extract a link or code.
  5. Return to the UI and assert the next state.

If each step exposes provider-specific details, the test becomes hard to read and harder to replace. A test should describe the user journey; the adapter should describe how a mailbox works. Its a small distinction, but it keeps product behavior visible.

This is also why a stable scenario ID is more useful than a random address alone. The ID can appear in logs, message metadata, and cleanup jobs. I keep that idea close to stable inbox scenario IDs, especially when several CI jobs run the same flow at once.

Define a small mail port

Start with the smallest interface the test actually needs. Do not copy an entire provider SDK into every browser test.

export type MailScenario = {
  id: string;
  address: string;
};

export type MailMessage = {
  id: string;
  subject: string;
  text: string;
};

export interface TestMailPort {
  createScenario(): Promise<MailScenario>;
  waitForMessage(input: {
    scenarioId: string;
    subject: string;
    timeoutMs: number;
  }): Promise<MailMessage>;
  dispose(scenarioId: string): Promise<void>;
}
Enter fullscreen mode Exit fullscreen mode

The port has a lifecycle, not only a getLatestMessage function. That matters because an old message can make a flaky test look green. The scenario ID and subject become part of the lookup, while the timeout makes waiting a deliberate choice.

For local component tests, the fake implementation can resolve immediately. For an end-to-end run, the implementation can allocate an isolated mailbox. The React test does not need to know which one is active. A disposable mail address is useful here as a delivery boundary, but it should be owned by the scenario and cleaned up after the run.

Keep React states separate from transport states

The UI should not render provider states such as MESSAGE_POLLING or MAILBOX_RETRYING. Those are useful diagnostic states, but they are not product states. Map them at the test boundary into a small set of user-visible states:

type VerificationState =
  | { kind: "idle" }
  | { kind: "submitting" }
  | { kind: "check-inbox"; address: string }
  | { kind: "verified" }
  | { kind: "error"; message: string };
Enter fullscreen mode Exit fullscreen mode

In React, this keeps the component focused on accessible labels, disabled buttons, and the next action. The test harness can still record transport timings and message IDs beside the browser trace. Mixing both models in one state object is a bit more easier at first, then expensive when the provider changes.

A useful contract test checks the adapter independently:

it("returns only a message for the requested scenario", async () => {
  const scenario = await mail.createScenario();
  await app.sendVerification(scenario.address);

  const message = await mail.waitForMessage({
    scenarioId: scenario.id,
    subject: "Verify your account",
    timeoutMs: 30_000,
  });

  expect(message.text).toContain("/verify");
});
Enter fullscreen mode Exit fullscreen mode

The browser test can then verify that the React screen changes after the verification link is used. It doesnt need to prove mailbox filtering and accessible UI behavior in the same assertion.

Make failures carry evidence

Timeouts are inevitable in integration tests. Unexplained timeouts are optional. When waitForMessage fails, include the scenario ID, expected subject, elapsed time, provider request ID, and the last observed delivery event. Do not dump the entire message into CI logs; links and tokens can become credentials in the wrong place.

A failure such as “scenario signup-42 saw 0 matching messages after 30s” is actionable. “Expected text not found” is not. In practise, this evidence saves more debugging time than another retry.

Also check the boring details. A label containing tem email or tempail can hide a typo in a fixture name, so normalize scenario metadata at the adapter boundary and keep the canonical ID in every log line. Small naming mistakes are not a security issue by themselves, but they make searches and cleanup less reliable.

Where replay safety fits

Verification links should have explicit expiry and single-use behavior. The test adapter can help by recording which message ID and token were consumed, but the backend remains responsible for rejecting a replay. For a deeper backend design, see these replay windows for email change tokens.

This split keeps responsibilities clear: the mail port proves delivery and isolation, while the application proves authorization and token semantics. A passing inbox check must never be treated as proof that a token is safe to reuse.

Q&A: choosing the right level of testing

Should every React test use a real mailbox?

No. Use a fake port for component and most workflow tests. Reserve a real delivery adapter for a small end-to-end suite that covers rendering, sending, parsing, and cleanup. That gives fast feedback without pretending that a mock proves delivery.

Should message bodies be stored in test artifacts?

Usually only for a short-lived local debug bundle. Prefer subject, message ID, scenario ID, and a redacted extraction result in CI. Retaining full bodies can expose verification URLs.

What should the timeout be?

Set it from the delivery path you are testing, then make it visible in the test name or diagnostics. A fixed, justified timeout is better than an unbounded poll that hides a broken worker.

A short implementation checklist

  • Define one typed mail port with create, wait, and dispose operations.
  • Give every scenario a unique ID and include it in logs.
  • Keep React states independent from provider retry states.
  • Test adapter filtering and cleanup separately from UI assertions.
  • Record useful metadata without retaining secrets or full message bodies.
  • Verify token expiry and replay behavior in the backend.
  • Run a small real-delivery suite alongside fast fake-transport tests.

The result is a cleaner developer experience: React tests explain product behavior, TypeScript protects the seams, and delivery failures arrive with enough evidence to fix them. That boundary may be small, but it keeps email from turning every signup test into a mystery.

Top comments (0)