How to Test Email Verification in Cypress: Receive Sign-Up Codes with cy.task

Test sign-up, reset and magic-link emails in Cypress: an address per test through cy.task, wait for the real email, read the code, and clean up afterwards.

By · · 12 min read

TypeScript code from this guide, in signup.cy.ts, where a Cypress test waits for an email with cy.task

Cypress runs your specs inside the browser, and a sign-up test needs something the browser cannot do: read the email your app sends. The answer is cy.task, which runs Node code next to Cypress. This tutorial gives each test an address of its own and mail that clears itself: a task creates the address, the spec submits the sign-up form with it, a second task waits for the code, and a third deletes the address.

It uses the Mailcycle TypeScript SDK. Mail is encrypted the moment it arrives, and the SDK opens it on the machine running the tests. If you use Playwright, the same idea is in Playwright email verification.

Quick answer: how to receive an email in a Cypress test

Define three tasks in cypress.config.ts that call the Mailcycle SDK, then use them from the spec. The wait task resolves with the decrypted email, and the spec takes the code from email.text:

cy.task<{ text: string }>('waitForEmail', { inboxId: inbox.id, since, subject: 'verify' }, { timeout: 70_000 }).then(
  (email) => {
    const code = email.text.match(/code is (\d{6})/)?.[1];
    cy.get('input[name=code]').type(code!);
  },
);

The rest of this guide builds the tasks and the spec around that call.

What you’ll build

  • A cypress.config.ts with three tasks: createInbox, waitForEmail and deleteInbox.
  • A spec that creates an address before each test, signs up with it, reads the code and deletes the address afterwards.
  • The two small config files Cypress needs to run TypeScript.

The flow is the same in every test: the browser submits the form, your app’s email provider delivers a real email, the test waits for it over the API, and the browser finishes the job. Nothing is stubbed between your app and the inbox, so the test covers your templates, sender settings and provider as they behave.

Flow: a Cypress test signs up with a fresh address, the app sends a verification email, Mailcycle receives it encrypted on arrival, and the code is read to finish sign-up
A Cypress test signs up with a Mailcycle address, waits for the verification email and reads the code from it.

Prerequisites

  • An app that sends real email from the environment you test. Usually staging, sending through your normal provider.
  • Node.js 20 or later and Cypress. Chrome is used for the run: Cypress marks its bundled Electron browser as deprecated.
  • A Mailcycle account with an API key. API keys start at the Operator plan, and the free 7-day Scale trial includes them, with no card. Create the account in the web app.
  • Your recovery phrase. Mail arriving at your addresses is sealed with keys derived from it, and the SDK opens it on the machine running the tests.

Step 1: Install Cypress and the Mailcycle SDK

npm install --save-dev cypress typescript @types/node mailcycle-sdk

mailcycle-sdk has no dependencies, ships its own types and runs on Node 20 or later. It is an ES module, so add "type": "module" to your package.json if it is not there already. Without it, Node tries to require() the SDK and stops with No "exports" main defined.

{
  "type": "module",
  "scripts": { "test:e2e": "cypress run --browser chrome" }
}

Cypress compiles TypeScript specs with ts-loader, which looks for a tsconfig.json in the project or in the cypress folder. Create cypress/tsconfig.json:

{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2022", "dom"],
    "types": ["cypress", "node"],
    "strict": true,
    "module": "esnext",
    "moduleResolution": "bundler"
  },
  "include": ["**/*.ts"]
}

Step 2: Create an API key

In the Mailcycle app, open API, then the Keys tab, name the key something like “Cypress tests” and choose Create key. The token is shown once. Put it and your phrase in the environment the tests run in:

export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export BASE_URL="https://staging.example.com"

In CI these become secrets passed to the test step with env:.

Step 3: Define the tasks

Cypress specs run in the browser, so the SDK calls go in Node, as tasks in cypress.config.ts:

import { defineConfig } from 'cypress';
import { Mailcycle } from 'mailcycle-sdk';

// One client for the whole run, made the first time a task needs it.
let client: Promise<Mailcycle> | undefined;
const mailcycle = () =>
  (client ??= Mailcycle.withApiKey({
    apiKey: process.env.MAILCYCLE_API_KEY!,
    phrase: process.env.MAILCYCLE_PHRASE!, // opens the mail on this machine
  }));

export default defineConfig({
  e2e: {
    baseUrl: process.env.BASE_URL ?? 'http://localhost:3000',
    supportFile: false,
    setupNodeEvents(on) {
      on('task', {
        // A new address for this test.
        async createInbox() {
          const address = await (await mailcycle()).addresses.create({ prefix: 'cy', retentionDays: 1 });
          return { id: address.id, email: address.emailAddress };
        },
        // Resolves with the first matching email received from `since` on.
        async waitForEmail({ inboxId, since, subject }: { inboxId: string; since: string; subject: string }) {
          const message = await (await mailcycle()).messages.waitFor({
            inboxId,
            since: new Date(since),
            subject,
            timeoutMs: 60_000,
          });
          return { subject: message.subject, from: message.from, text: message.text };
        },
        // Removes the address and its mail.
        async deleteInbox(inboxId: string) {
          await (await mailcycle()).addresses.delete(inboxId);
          return null; // a task must not return undefined
        },
      });
    },
  },
});

What each piece does:

  • Mailcycle.withApiKey({ apiKey, phrase }) builds a client that can create addresses that receive mail and open what arrives. It checks that the phrase belongs to the key’s account, so a mismatched pair fails at the start with phrase_mismatch rather than as a timeout later.
  • addresses.create({ prefix: 'cy' }) returns an address like cy-x7k2@…: your prefix plus a random ending. retentionDays: 1 clears any mail the clean-up misses after a day, not the default seven.
  • messages.waitFor() resolves with the next matching message, already decrypted. It counts mail received from since onwards, including mail that landed before the listener was up, so a fast app cannot beat the test to it.
  • since is an ISO string. Task arguments are serialised, so the spec sends a string and the task turns it back into a Date.
  • return null matters: a task must return something serialisable, and undefined fails it.
  • addresses.delete() removes the address and its mail. A deleted address is retired and never issued to anyone again.

Step 4: Write the spec

Create cypress/e2e/signup.cy.ts. Change the selectors and the button labels to match your app:

describe('sign-up', () => {
  let inbox: { id: string; email: string };

  beforeEach(() => {
    cy.task<{ id: string; email: string }>('createInbox').then((created) => {
      inbox = created;
    });
  });

  afterEach(() => {
    cy.task('deleteInbox', inbox.id);
  });

  it('verifies the account with the emailed code', () => {
    const since = new Date().toISOString();
    cy.visit('/');
    cy.get('input[name=email]').type(inbox.email);
    cy.contains('button', 'Create account').click();
    cy.contains('h2', 'Check your email');

    cy.task<{ text: string }>('waitForEmail', { inboxId: inbox.id, since, subject: 'verify' }, { timeout: 70_000 }).then(
      (email) => {
        const code = email.text.match(/code is (\d{6})/)?.[1];
        expect(code, 'six-digit code').to.be.a('string');
        cy.get('input[name=code]').type(code!);
      },
    );
    cy.contains('button', 'Verify').click();
    cy.contains('h1', 'Welcome').should('be.visible');
  });
});

Run it with npx cypress run --browser chrome.

Three details keep it reliable:

  • Take since before the click that sends the email. The wait then finds the email whichever way the race between your app and your test goes.
  • Give cy.task a timeout longer than the wait. The task waits up to 60 seconds, so the command’s timeout is 70 seconds. Cypress’s default task timeout is shorter.
  • Anchor the pattern on the words around the code. /code is (\d{6})/ skips order numbers and dates that also have six digits. Use the capture group.

An address per test keeps tests independent

beforeEach creates the address and afterEach deletes it, even when the test fails. A retried test gets a new address and a new email, never the last attempt’s spent code, so retries and parallel runs do not interfere. Each test’s email arrives in an inbox only that test can read, and retentionDays: 1 clears anything left over the next day.

The same three tasks cover a magic link or a reset link: request the email in the spec, wait for it with waitForEmail, take the first link from email.text that points at your app’s host, and cy.visit(link). Seed the user through your own test API first, so the reset test does not depend on the sign-up test.

Wrap the flow in a custom command

Once the sign-up works in one spec, you will want it in many. Cypress custom commands are the place for it. Add one in cypress/support/commands.ts and register it in cypress/support/e2e.ts (set supportFile back to that path in the config).

declare global {
  namespace Cypress {
    interface Chainable {
      signUpWithInbox(): Chainable<{ id: string; email: string }>;
    }
  }
}

Cypress.Commands.add('signUpWithInbox', () => {
  return cy.task<{ id: string; email: string }>('createInbox').then((inbox) => {
    const since = new Date().toISOString();
    cy.visit('/');
    cy.get('input[name=email]').type(inbox.email);
    cy.contains('button', 'Create account').click();
    cy.task<{ text: string }>('waitForEmail', { inboxId: inbox.id, since, subject: 'verify' }, { timeout: 70_000 })
      .then((email) => cy.get('input[name=code]').type(email.text.match(/code is (\d{6})/)![1]));
    cy.contains('button', 'Verify').click();
    return cy.wrap(inbox);
  });
});

A spec that needs a signed-in user then starts with cy.signUpWithInbox(), and an afterEach that deletes the returned address keeps the account tidy. Keep the command short and put assertions in the specs, so a failure points at the test and not at a helper.

Cache the verified user with cy.session

Signing up through the email takes seconds, and doing it before every test adds up. After the first verification, cy.session can store the logged-in cookies and local storage and restore them in later tests.

Cypress.Commands.add('loginAsVerifiedUser', (email: string, password: string) => {
  cy.session([email], () => {
    cy.visit('/login');
    cy.get('input[name=email]').type(email);
    cy.get('input[name=password]').type(password, { log: false });
    cy.contains('button', 'Sign in').click();
    cy.contains('h1', 'Dashboard');
  });
});

Run the email-based sign-up once in a before hook, then restore the session in each spec. The email flow is tested where it matters, and the rest of the suite skips it.

Retries and flaky mail

Cypress can retry a failed test, set with retries: { runMode: 2, openMode: 0 } in the config. For email tests this is safe, because beforeEach runs again and creates a new address, so a retry never sees the previous attempt’s mail. If a test passes only on a retry, look at your provider’s delivery time before you raise a timeout: a slow queue in staging is a real finding, and the retry hides it. Log how long each waitForEmail took, and watch for the number creeping up.

Assert the network call as well

The email is the end of a chain that starts with a request. cy.intercept lets the spec wait for the sign-up request and check its status before it starts listening for the message, which separates “the app never sent a request” from “the request worked and the email never came”.

cy.intercept('POST', '/api/signup').as('signup');
cy.contains('button', 'Create account').click();
cy.wait('@signup').its('response.statusCode').should('eq', 201);

When this assertion passes and the email still does not arrive, the problem is in your mail provider, not in the form.

Run the suite in GitHub Actions

The official Cypress action installs, caches and runs the suite. Pass the Mailcycle key and phrase as secrets and the staging URL as an environment variable.

jobs:
  cypress:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: cypress-io/github-action@v6
        with:
          browser: chrome
        env:
          MAILCYCLE_API_KEY: ${{ secrets.MAILCYCLE_API_KEY }}
          MAILCYCLE_PHRASE: ${{ secrets.MAILCYCLE_PHRASE }}
          BASE_URL: https://staging.example.com

Because the tasks run in the same Node process that Cypress starts, the secrets only need to be in the job’s environment. Upload screenshots and videos as artifacts on failure, and remember the screenshot can show a code, so treat artifacts as private.

Typed tasks

Tasks take and return loosely typed values, so a small shared type keeps the config and specs honest. Export type Inbox = { id: string; email: string } from a file both import, and use it in cy.task<Inbox>('createInbox') and in the task’s return. A typo in a field name then fails at compile time and not as a confusing undefined in the middle of a run.

Test an invitation with two addresses

Invitations involve two people, and a real inbox lets one spec play both. Create one address for the owner and one for the invitee, sign the owner in, send the invitation to the second address, then wait on the second inbox and follow the link.

it('lets an invited teammate join', () => {
  cy.task<Inbox>('createInbox').then((invitee) => {
    const since = new Date().toISOString();
    cy.loginAsVerifiedUser(ownerEmail, ownerPassword);
    cy.visit('/team');
    cy.get('input[name=invite]').type(invitee.email);
    cy.contains('button', 'Send invite').click();

    cy.task<{ text: string }>('waitForEmail', { inboxId: invitee.id, since, subject: 'invited' }, { timeout: 70_000 })
      .then((email) => {
        const link = email.text.match(/https:\/\/staging\.example\.com\/join\?\S+/)![0];
        cy.visit(link);
      });
    cy.contains('h1', 'Join the team');
    cy.task('deleteInbox', invitee.id);
  });
});

The same idea covers any flow with a second person: a shared document, a transfer of ownership or a team invite. Each person gets an address, and the spec reads each inbox on its own.

A full password reset test

A reset has three parts the test can check: the request, the email and the new password. Request the reset for a seeded user’s address, wait for the message, follow the link and set a new password, then sign in with it.

cy.visit('/forgot-password');
cy.get('input[name=email]').type(user.email);
cy.contains('button', 'Send reset link').click();

cy.task<{ text: string }>('waitForEmail', { inboxId: user.inboxId, since, subject: 'reset' }, { timeout: 70_000 })
  .then((email) => cy.visit(email.text.match(/https:\/\/staging\.example\.com\/reset\?\S+/)![0]));
cy.get('input[name=password]').type('a-new-long-password', { log: false });
cy.contains('button', 'Save password').click();
cy.contains('h1', 'Dashboard');

A good extra assertion is to visit the same link a second time and expect the app to refuse it. That proves the token is single use, which a captured message can never tell you.

Check a receipt and its attachment

Order emails often carry a PDF. Add a task that fetches the first attachment and returns its size and type, so the spec can assert the file exists without the browser touching it.

async firstAttachment({ inboxId, since }: { inboxId: string; since: string }) {
  const mc = await mailcycle();
  const message = await mc.messages.waitFor({ inboxId, since: new Date(since), timeoutMs: 60_000 });
  const bytes = await mc.messages.attachment(message, 0);
  return { name: message.attachments[0].filename, size: bytes.length, type: message.attachments[0].mimeType };
},

The spec can then assert that the name ends in .pdf and that the size is above a few kilobytes, which catches the receipt that arrives with an empty file. Return only small values from a task, never the file bytes, because task results travel through Cypress’s serialiser.

Keep the secrets safe

Two secrets are involved: the API key and the recovery phrase. Both belong in your CI secret store and in a local .env file that is ignored by git, never in cypress.config.ts, a fixture or cypress.env.json under version control. Cypress prints the config when a run starts in some modes, so read secrets from process.env inside the task, as the config above does, rather than passing them through Cypress.env. Rotate the API key from the app if it ever lands in a log.

Why a real inbox beats stubbing the mail step

Many Cypress suites skip the email by stubbing the sign-up response or by adding a test-only route that returns the code. Both are quick, and both leave the real path untested. A stub proves your form handles a made-up response. A real address proves your provider accepted the message, the template filled in the code, the sender looked right and the link or code worked when the person used it. Keep a stubbed spec for fast feedback on form behaviour, and keep one real-inbox spec per flow in the nightly run. Together they cover speed and truth.

Debug an email test in the Cypress runner

When a spec fails in the interactive runner, the command log tells most of the story. The waitForEmail task shows as a single entry, so add a cy.log before and after it with the address, which gives you something to look up. If the task times out, open the address in the Mailcycle app with your recovery phrase and check whether anything arrived. An empty inbox points at your app or your provider. A message that is there but did not match points at the subject filter or the since time, which is usually set after the click and not before it. Run the spec headed once with npx cypress open, since a click that works headless but not headed often shows a layout problem.

Run specs in parallel and clean up after

Cypress Cloud can split a run across machines, and each machine runs its own tasks with its own client. That is safe here, because every test creates its own address, so two machines never read each other’s mail. If a run is cancelled halfway, the one day retention on each address clears whatever was left, and a small cleanup script can delete addresses with the cy prefix older than a day. Name prefixes by suite, such as cy-signup and cy-invite, so the leftovers are easy to recognise.

Component tests do not need the inbox

Cypress component tests mount a single component, so a sign-up form can be tested without any email at all: assert that submitting calls your handler with the typed address. Keep the real inbox for end-to-end specs, where the email is part of what you are proving. A suite with many fast component tests and a few real-mail specs finishes quickly and still tells you when the mail path breaks.

Troubleshooting

You are attempting to run a TypeScript file, but do not have TypeScript installed. Install typescript (Step 1).

TsConfigNotFoundError: No tsconfig.json found. Add cypress/tsconfig.json from Step 1.

The cy.task call times out. The command’s timeout is shorter than the wait. Raise it above the timeoutMs in the task.

waitFor rejects with code: 'timeout'. No matching email arrived in time. Check, in order: that the app really sent it (your provider’s logs), that the subject filter matches the real subject, and that staging can send to outside addresses. Some providers limit new or sandboxed accounts to recipients you have verified; Amazon SES’s sandbox is one example.

The task fails with undefined. A task must return a value, so return null from a task with nothing to give back.

No "exports" main defined. Add "type": "module" to package.json (Step 1).

phrase_mismatch or 403 plan_required. The phrase belongs to a different account from the API key, or the account is on a plan without API keys. See Errors and Authentication.

Next steps

FAQ

Can Cypress receive and read emails?

Not from the browser, but Cypress runs Node code through cy.task, defined in setupNodeEvents in cypress.config.ts. Put the Mailcycle SDK calls in tasks (create an address, wait for an email, delete the address) and call them from the spec with a timeout longer than the wait.

How do I get a verification code from an email in a Cypress test?

Call a task that waits for the message, then match the code in its plain-text body, for example email.text.match(/code is (\d{6})/). Anchoring the pattern on the words around the code avoids picking up other long numbers in the email.

Why does a Cypress task return `null` instead of nothing?

A cy.task handler must return a value that can be serialised, and returning undefined fails the task. Return null from a task that has nothing to give back, like the one that deletes an address.

Should every Cypress test get its own email address?

Usually, yes. A fresh address per test means no test can read another test's email, so retries start clean and nothing depends on test order. Create the address in beforeEach and delete it in afterEach.

Why do I need a tsconfig.json for Cypress and TypeScript?

Cypress compiles .ts specs with ts-loader, which needs typescript installed and a tsconfig.json in the project or in the cypress folder. Without them the run stops with a message about TypeScript.

Which Mailcycle plan do I need for email tests?

The examples use an API key with your recovery phrase, which needs the Operator plan or above; the free 7-day Scale trial covers it, with no card. A script signed in with Mailcycle.signIn({ phrase }) can receive on every plan, Free included. See plans and limits.

How do I reuse the email steps across many Cypress specs?

Wrap them in a custom command with Cypress.Commands.add, such as cy.signUpWithInbox(). The command creates the address, submits the form, waits for the email and types the code, so each spec starts one line away from a verified user.

Will Cypress retries send the sign-up email twice?

A test retry runs the test again, including beforeEach, so it creates a new address and a new email. Because each attempt has its own address, a retry never reads the last attempt's spent code.

Receive email in code