saci.cc
← Blog

Email verification in Cypress with cy.task

Cypress runs tests inside the browser, and that changes how you read an email: the test code can't hold the API key or keep a request open for 25 seconds without getting in the way. The answer is to run the saci.cc client in the Node process Cypress already has, with cy.task. The test asks "create an inbox" and "wait for the code", and gets strings back.

The key and the package

Sign in with GitHub on your account page, create a free key and install the client:

npm install --save-dev saci.cc
export SACI_API_KEY=saci_...

The client reads SACI_API_KEY from the Cypress process's environment, not the browser's. That's why you shouldn't use Cypress.env for the key: anything there is visible to code running on the page.

The tasks

Tasks run in Node, in setupNodeEvents:

// cypress.config.ts
import { defineConfig } from "cypress";
import { Saci } from "saci.cc";

// Reads the key from SACI_API_KEY
const saci = new Saci();

export default defineConfig({
  e2e: {
    baseUrl: "http://localhost:3000",
    // A task can wait 60 s by default; emails sometimes take longer
    taskTimeout: 90_000,
    setupNodeEvents(on) {
      on("task", {
        async createInbox() {
          return (await saci.createInbox()).address;
        },
        // after: only emails received after that moment
        waitForCode({ address, after }: { address: string; after: string }) {
          return saci.inbox(address).waitForCode({ after, timeout: 80_000 });
        },
        waitForLink({ address, after, match }: { address: string; after: string; match?: string }) {
          return saci.inbox(address).waitForLink({ after, match, timeout: 80_000 });
        },
      });
    },
  },
});

Two details prevent flaky tests. A taskTimeout longer than the client's timeout makes the error come from saci.cc (No verification code arrived at ... within 80000 ms), which says what happened, instead of a generic Cypress timeout. And after makes sure an old email, from an earlier attempt of the same test, isn't read as the new one.

Commands, so the test reads well

Instead of calling cy.task with strings everywhere, add commands:

// cypress/support/commands.ts
Cypress.Commands.add("createInbox", () => cy.task<string>("createInbox"));

Cypress.Commands.add("waitForCode", (address: string, after: Date) =>
  cy.task<string>("waitForCode", { address, after: after.toISOString() }),
);

Cypress.Commands.add("waitForLink", (address: string, after: Date, match?: string) =>
  cy.task<string>("waitForLink", { address, after: after.toISOString(), match }),
);

// Types so TypeScript knows the commands
declare global {
  namespace Cypress {
    interface Chainable {
      createInbox(): Chainable<string>;
      waitForCode(address: string, after: Date): Chainable<string>;
      waitForLink(address: string, after: Date, match?: string): Chainable<string>;
    }
  }
}

export {};

The sign-up test

// cypress/e2e/signup.cy.ts
describe("sign-up", () => {
  it("confirms the email with the code", () => {
    cy.createInbox().then((address) => {
      // Note the time before submitting the form
      const started = new Date();

      cy.visit("/signup");
      cy.get("input[name=email]").type(address);
      cy.get("input[name=password]").type("correct horse battery staple");
      cy.get("button[type=submit]").click();

      cy.waitForCode(address, started).then((code) => {
        cy.get("input[name=code]").type(code);
        cy.get("button[type=submit]").click();
      });

      cy.contains("Welcome").should("be.visible");
    });
  });
});

saci.cc pulls the code out of the email when it arrives, so the test needs no regex. Each run creates a new inbox with a random address, and parallel tests don't read each other's email.

If your app sends a link instead of a code, use waitForLink. The third argument picks the right link when the email has several:

it("signs in with the magic link", () => {
  cy.createInbox().then((address) => {
    const requested = new Date();
    cy.visit("/login");
    cy.get("input[name=email]").type(address);
    cy.get("button[type=submit]").click();

    cy.waitForLink(address, requested, "/auth/callback").then((link) => cy.visit(link));
    cy.url().should("include", "/dashboard");
  });
});

cy.visit works directly when the link is on the same domain as baseUrl. If your email provider rewrites links to track clicks, the link points to another domain and Cypress complains. In that case, turn off click tracking in the test environment, which is simplest, or use cy.origin.

In CI

Save the key as a secret and pass it to the Cypress step. On GitHub Actions, with the official action:

- uses: cypress-io/github-action@v6
  with:
    start: npm start
  env:
    SACI_API_KEY: ${{ secrets.SACI_API_KEY }}

Each wait uses few requests, because the API holds the response until the email arrives. On the Free plan, with 120 requests per minute, you can run dozens of email tests in parallel. The GitHub Actions post covers shards and limits in more detail.

In short

  • Run the saci.cc client in Node with cy.task, and keep the key in SACI_API_KEY, out of the browser.
  • Raise taskTimeout to 90 seconds and pass after with the time from before the action.
  • Use waitForCode for codes and waitForLink for confirmation and sign-in links.
  • On Playwright, Selenium or Puppeteer? See the Playwright guide and the Selenium and Puppeteer one.