# Email testing in Cypress

> A Cypress test that waits for an email and reads the code inside it, with the API key kept out of the browser. No arbitrary cy.wait.
> https://facteur.eu/en/cypress-email-testing

## Waiting for mail without cy.wait

Cypress runs your test inside the browser, which raises two problems for reading email: the API key must not be there, and the network call answers to the origin of the page under test. One Node task solves both.

## The config, then the test

The task lives in the Cypress process, where the key can stay. The test only ever sees a command.

### The key stays on the Node side

Your spec is served to a page: a key written into it would be a key in a page’s JavaScript. The task keeps it on the other side.

### cy.task yields a value, so the chain continues

The message comes back into the usual command queue, and .should() behaves as it does on a cy.get().

### The attempt number is in the address

Without it, a retried test reads the mail from its own first attempt and passes for the wrong reason, exactly when something is already flaky.

## Why there is no cy.wait

## The application that sends this email

What is left is an application that sends the message this test waits for. La Belle Etoile is one, open to anyone: order a lamp, give it your test mailbox address, and the confirmation arrives with its code. It serves eight journeys, one of which mails nothing at all: that is the one that exercises a test asserting no email went out. It only ever mails a Facteur address, which is what stops it being a relay for anyone else.

## The Cypress plugin, if you want it

It installs in one line: npm i -D cypress-facteur. The version above is still the one that needs nothing installed, in about thirty lines you keep.
