Skip to content
Facteur

Type at least two characters.

Receive email in a Playwright test

The complete test that searches for an email every second, reads the code it contains and carries on with the journey, with no sleep. The Playwright plugin installs from npm.

A sign-up journey ends in a mailbox, and your test has to read what arrives there. Here is the whole file. It calls the API directly with a key and needs no package. The Facteur Playwright plugin does the same with less code: see the end of this page.

Before you start

Two things, and nothing else:

  1. A read-only API key. Create it in Settings → API keys and put it in your continuous integration secrets, as FACTEUR_API_KEY. The test below creates nothing: it reads. See API keys.
  2. The identifier of your inbox, the eight characters before .inbox in its receiving address.
import { expect, test } from '@playwright/test';

const KEY = process.env.FACTEUR_API_KEY!;
const INBOX = 'j3k9x2mq';

/** Searches every second until the message arrives, twenty seconds at most. */
const waitFor = async (sentTo: string, since: Date) => {
  const search = new URLSearchParams({ inbox: INBOX, sentTo, since: since.toISOString() });
  for (let attempt = 0; attempt < 20; attempt++) {
    const response = await fetch(`https://api.facteur.eu/messages?${search}`, {
      headers: { authorization: `Bearer ${KEY}` },
    });
    if (response.status !== 429) {
      if (!response.ok) throw new Error(`Facteur answered ${response.status}`);
      const { messages } = await response.json();
      if (messages[0]) return messages[0];
    }
    await new Promise((r) => setTimeout(r, 1000));
  }
  throw new Error(`no message for ${sentTo} within 20 s`);
};

test('the verification link activates the account', async ({ page }) => {
  const tag = `run-${Date.now()}`;

  // Noted before the click: only an email that arrives after it counts.
  const since = new Date();

  // The sign-up journey of YOUR application.
  await page.goto('/signup');
  await page.getByLabel('Email').fill(`signup+${tag}@${INBOX}.inbox.facteur.eu`);
  await page.getByRole('button', { name: 'Create my account' }).click();

  const message = await waitFor(`signup+${tag}@`, since);
  expect(message.status).toBe('parsed');
  await page.goto(message.links[0]);

  await expect(page.getByText('Account verified')).toBeVisible();
});

Note the time before the action

It is the only line whose order matters. since is taken before the click: an email that arrives during the click still counts, and an email sent to the same address by an earlier run does not. Taken after, it could leave out a fast email, and you would see that flaw the day your continuous integration speeds up.

One address per test, with nothing to create

Any address that ends with the domain of your inbox arrives in it. You therefore have no call to make to create signup+run-1734@j3k9x2mq.inbox.facteur.eu: you just write it. That is what lets sixteen parallel tests share one inbox without stealing each other's emails. Each test that waits sends about one request a second, and a key may send 600 a minute. Past that, the answer is 429 with a Retry-After, and the loop above tries again a second later: the suite slows down instead of failing.

Put the name of the test and the attempt number in the tag. Without the number, a retried test rereads the email of its first attempt and passes for the wrong reason, precisely when something is already unstable.

Read status before anything else

An accepted email exists before it is parsed. For a few milliseconds it has no subject, no code and no links. The status field tells "there is no code in this message" from "the code is not extracted yet". Search returns only parsed messages by default, so the case only comes up if you ask for status: any.

The code is already out of the message

messages[0].otp carries the one-time code, extracted on reception. You write no regular expression, and you have nothing to fix the day the email template changes.

The links are there too: messages[0].links holds the list, in the order they appear, each as plain text. Pass one straight to page.goto().

The Playwright plugin

The playwright-facteur plugin writes the address of each test and the wait for the message for you, and attaches the message received to the report. It installs from npm, at version 2.0.0 or later:

npm i -D playwright-facteur

The test above works with or without it.