Cypress

A Cypress test that waits for the code in a sign-up mail with cy.request and types it in.

Setup

Written for Cypress 16, whose cy.env reads the key. Run Cypress with your API key in MAYFLY_API_KEY.

cypress.config.js
const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: { baseUrl: "https://app.example.test" },
  // From the environment, so the key never lands in the repository.
  env: { MAYFLY_API_KEY: process.env.MAYFLY_API_KEY },
});

Two commands

cy.mayflyNow reads Mayfly's clock from the Date header of one of its answers. cy.waitForMail holds until the mail has arrived, so its timeout outlasts the wait's. A 404 from the wait fails the test with Mayfly's answer: wait_timeout when no mail arrived.

cypress/support/e2e.js
const MAYFLY = "https://mayfly.aravaltech.com";

const mayflyHeaders = () =>
  cy
    .env(["MAYFLY_API_KEY"])
    .then(({ MAYFLY_API_KEY }) => ({ Authorization: `Bearer ${MAYFLY_API_KEY}` }));

// Mayfly's clock, from the Date header of one of its answers.
// Take it before your app sends the mail.
Cypress.Commands.add("mayflyNow", () =>
  mayflyHeaders().then((headers) =>
    cy
      .request({ url: `${MAYFLY}/api/v1/mailboxes`, qs: { limit: 1 }, headers })
      .then((response) => new Date(response.headers.date).toISOString()),
  ),
);

// The newest mail to `to` since `since`, once it has arrived and been read.
Cypress.Commands.add("waitForMail", (to, since) =>
  mayflyHeaders().then((headers) =>
    cy
      .request({
        url: `${MAYFLY}/api/v1/wait`,
        qs: { to, since, timeout: 30 },
        headers,
        timeout: 40_000, // longer than the wait itself
      })
      .its("body"),
  ),
);

The test

Take since before the app sends anything, so no older mail to the address can be picked up. Put your own app's page and fields in, and your private test domain in place of <your-name>: it's on Overview.

cypress/e2e/sign-up.cy.js
const DOMAIN = "<your-name>.qa.aravaltech.info";

it("sign-up sends a code that works", () => {
  const email = `signup-${Date.now()}@${DOMAIN}`;

  cy.mayflyNow().then((since) => {
    cy.visit("/sign-up");
    cy.get("input[name=email]").type(email);
    cy.contains("button", "Send code").click();

    cy.waitForMail(email, since).then((mail) => {
      expect(mail.otp, "Mayfly found no code in the mail").to.not.equal(null);
      cy.get("input[name=code]").type(mail.otp.value);
      cy.contains("button", "Verify").click();
    });
  });
});

A link from the mail is in mail.links. Mail is written by strangers, so only visit a link to your own app, as the Playwright guide does.

NextAny language