Receive email in a Cypress test
A Node task that keeps the key out of the browser, and a test that searches for the email every second instead of pausing a fixed number of seconds. The Cypress plugin installs from npm.
Cypress runs your test in the browser, which raises two problems for reading an email: your API key has no business in a page, and the network call answers to the origin of the site under test. A Node task solves both at once.
This page calls the API directly, with no package. The Facteur Cypress plugin does the same: see the end of this page.
Before you start
Two things, and nothing else:
- A read-only API key. Create it in
Settings → API keys
and put it in your continuous integration secrets, as
FACTEUR_API_KEY. See API keys. - The identifier of your inbox, the eight characters before
.inboxin its receiving address. It isj3k9x2mqin the examples that follow.
The configuration, where the key can stay
// cypress.config.js
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
setupNodeEvents(on) {
on('task', {
async waitForEmail({ sentTo, since }) {
const search = new URLSearchParams({ inbox: 'j3k9x2mq', sentTo, since });
// Searches every second, thirty seconds at most.
for (let attempt = 0; attempt < 30; attempt++) {
const response = await fetch('https://api.facteur.eu/messages?' + search, {
headers: { authorization: 'Bearer ' + process.env.FACTEUR_API_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));
}
return null;
},
});
},
},
});
This file runs in the Cypress process, not in the page. The key is read from the environment there and never reaches the browser.
The test
it('the code arrives by email', () => {
const tag = 'signup-a' + (Cypress.currentRetry ?? 0) + '-' + Date.now();
// Noted before the action: only an email that arrives after it counts.
const since = new Date().toISOString();
// The sign-up journey of YOUR application.
cy.visit('/signup');
cy.get('[name=email]').type(tag + '@j3k9x2mq.inbox.facteur.eu');
cy.contains('button', 'Create my account').click();
cy.task('waitForEmail', { sentTo: tag + '@', since }, { timeout: 40000 }).should((message) => {
expect(message, 'no email arrived').to.not.be.null;
expect(message.otp).to.match(/^[0-9]{6}$/);
});
});
Why there is no cy.wait
The task searches every second and returns as soon as the message is there, thirty
seconds at most. A fixed pause is either too short on a loaded machine, or time lost on
every run. since, noted before the click, keeps out the email of an earlier run.
The timeout passed to cy.task must stay above the thirty seconds of the task:
forty seconds here, otherwise Cypress gives up on the task before the answer arrives,
and the failure blames the wrong culprit.
The attempt number in the address
Cypress.currentRetry is 0 on the first attempt. Without it, a retried test rereads the
email of its first attempt and passes for the wrong reason, precisely when something is
already unstable.
One inbox is enough for the whole suite
Any address ending with the domain of the inbox arrives in it, with nothing to create. Every test therefore receives at its own address in the same inbox. On a plan that includes a single inbox, that is the difference between a suite that runs and a suite that hits a ceiling.
The Cypress plugin
The cypress-facteur plugin keeps the key out of the browser and provides chainable
commands, which the configuration above does by hand. It installs from npm, at version
2.0.0 or later:
npm i -D cypress-facteur
The configuration above works with or without it.