AssertInbox

Cypress sign-up with an emailed code: an example project

This is a small Cypress project for testing a sign-up that emails a code. It signs up on the AssertInbox practice app, a fake product that emails a six-digit code and a confirmation link, waits for that email through AssertInbox tasks, types the code into the form and checks that the account is verified. A second test opens the emailed link instead. Nothing is mocked: the mail is real and arrives at a real address, and you only need a key because the practice app is hosted for you.

Not run yet. Cypress could not be installed where this example was written, because its test runner binary could not be downloaded, so these files were syntax-checked only and the tests have not been run. The identical flow did run for real in the Playwright example and the pytest example. The project asks for Cypress major version 16 (^16.5.0) and Node 18 or newer.

Get a key

You need an AssertInbox key and its namespace. Get a key in one click: no email address or card is needed. The key is shown once, so keep it. Then export ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE (the namespace is shown with the key).

Download

Run these lines in an empty folder. They fetch every file below, each served as it is in the repository.

curl --create-dirs -fsSo package.json https://assertinbox.com/examples/cypress-signup-otp/package.json
curl --create-dirs -fsSo cypress.config.js https://assertinbox.com/examples/cypress-signup-otp/cypress.config.js
curl --create-dirs -fsSo cypress/e2e/signup.cy.js https://assertinbox.com/examples/cypress-signup-otp/cypress/e2e/signup.cy.js
curl --create-dirs -fsSo cypress-assertinbox.cjs https://assertinbox.com/examples/cypress-signup-otp/cypress-assertinbox.cjs
curl --create-dirs -fsSo .github/workflows/e2e.yml https://assertinbox.com/examples/cypress-signup-otp/ci/github-actions.yml
curl --create-dirs -fsSo README.md https://assertinbox.com/examples/cypress-signup-otp/README.md

Run it

npm install
export ASSERTINBOX_KEY=ai_...
export ASSERTINBOX_NAMESPACE=yournamespace
npx cypress run

By default the tests use the practice app at https://assertinbox.com/practice. Set PRACTICE_URL to point at another copy, and use npx cypress open to watch the tests in a browser.

The files

package.json

{
  "name": "assertinbox-cypress-signup-otp",
  "private": true,
  "scripts": {
    "test": "cypress run"
  },
  "devDependencies": {
    "cypress": "^16.5.0"
  }
}

cypress.config.js

const { defineConfig } = require("cypress");
const { registerAssertInboxTasks } = require("./cypress-assertinbox.cjs");

// The practice app is a fake product that emails a code and a link to AssertInbox addresses.
const PRACTICE = (process.env.PRACTICE_URL || "https://assertinbox.com/practice").replace(/\/+$/, "");

module.exports = defineConfig({
  env: { practiceUrl: PRACTICE },
  e2e: {
    supportFile: false,
    setupNodeEvents(on) {
      // The tasks run in Node, so the key never reaches the browser.
      registerAssertInboxTasks(on, { baseUrl: process.env.ASSERTINBOX_URL || undefined });
    },
  },
});

cypress/e2e/signup.cy.js

describe("practice app sign-up", () => {
  const practice = Cypress.env("practiceUrl");

  // A fresh address for every test: the task returns a new tag each time.
  function signUp(name) {
    return cy.task("assertinbox:address", name).then(({ tag, address }) => {
      cy.visit(practice + "/signup");
      cy.get("#email").type(address);
      cy.contains("button", "Create account").click();
      cy.location("pathname").should("eq", new URL(practice).pathname + "/verify");
      return cy.wrap(tag);
    });
  }

  it("verifies with the emailed code", () => {
    signUp("code").then((tag) => {
      cy.task("assertinbox:waitForOtp", { tag }, { timeout: 90000 }).then((code) => {
        cy.get("#code").type(code);
        cy.contains("button", "Verify").click();
        cy.get("#result").should("contain", "Your email is verified");
      });
    });
  });

  it("confirms with the emailed link", () => {
    signUp("link").then((tag) => {
      cy.task("assertinbox:waitForLink", { tag }, { timeout: 90000 }).then((link) => {
        cy.visit(link);
        cy.get("#result").should("contain", "Your email is confirmed");
      });
    });
  });
});

cypress-assertinbox.cjs

The AssertInbox Cypress tasks, identical to /sdk/cypress-assertinbox.cjs.

// AssertInbox Cypress tasks. MIT License. Node 18+ (global fetch). Use in cypress.config.js: registerAssertInboxTasks(on)
const BASE = "https://assertinbox.com";

function clean(value, max) {
  return String(value).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max);
}

// Task arguments are one value: a tag string or an options object.
function asOptions(arg) {
  if (arg === undefined || arg === null) return {};
  return typeof arg === "string" ? { tag: arg } : { ...arg };
}

// Cypress needs serialisable results: undefined becomes null.
function plain(value) {
  return value === undefined ? null : JSON.parse(JSON.stringify(value));
}

function registerAssertInboxTasks(on, { baseUrl = BASE, fetch: fetchFn } = {}) {
  const doFetch = fetchFn || ((...a) => globalThis.fetch(...a));
  const settings = () => {
    const key = process.env.ASSERTINBOX_KEY;
    const namespace = process.env.ASSERTINBOX_NAMESPACE;
    if (!key || !namespace) throw new Error("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE. Create a key at https://assertinbox.com/start");
    return { key, namespace };
  };

  async function wait(arg) {
    const { key } = settings();
    const { tag, timeout = 25, from, subject, after, since, retries = 2 } = asOptions(arg);
    if (!tag) throw new Error("tag is required");
    const q = new URLSearchParams();
    for (const [k, v] of Object.entries({ tag, timeout, from, subject, after, since })) if (v !== undefined && v !== null && v !== "") q.set(k, String(v));
    for (let attempt = 0; ; attempt++) {
      const res = await doFetch(baseUrl.replace(/\/+$/, "") + "/v1/wait?" + q, { headers: { Authorization: "Bearer " + key } });
      const body = await res.json().catch(() => ({}));
      if (res.ok) return body;
      if (res.status === 408 && attempt < retries) continue;
      throw new Error("AssertInbox " + (body.error || "http_" + res.status) + (body.message ? ": " + body.message : ""));
    }
  }

  on("task", {
    "assertinbox:address"(arg) {
      const { namespace } = settings();
      const { name = "user" } = asOptions(typeof arg === "string" ? { name: arg } : arg);
      const tag = clean(name, 16) + "-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
      return { tag, address: namespace + "." + tag + "@" + new URL(baseUrl).hostname.replace(/^www\./, "") };
    },
    async "assertinbox:wait"(arg) {
      return plain(await wait(arg));
    },
    async "assertinbox:waitForOtp"(arg) {
      const message = await wait(arg);
      if (!message.otp) throw new Error('No code found in the email with subject "' + message.subject + '"');
      return message.otp;
    },
    async "assertinbox:waitForLink"(arg) {
      const message = await wait(arg);
      if (!message.magic_link) throw new Error('No link found in the email with subject "' + message.subject + '"');
      return message.magic_link;
    },
  });
}

module.exports = { registerAssertInboxTasks };

.github/workflows/e2e.yml

name: e2e
on:
  push:
  pull_request:
jobs:
  cypress:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm install
      - run: npx cypress run
        env:
          ASSERTINBOX_KEY: ${{ secrets.ASSERTINBOX_KEY }}
          ASSERTINBOX_NAMESPACE: ${{ vars.ASSERTINBOX_NAMESPACE }}

README.md

# Cypress sign-up with an emailed code

A Cypress project that signs up on the AssertInbox practice app, reads the emailed code (and, in a second test, the emailed link) through AssertInbox tasks that run in Node, and checks the result. It needs a key and nothing else: no app of your own.

Cypress major version: 16 (`cypress` ^16.5.0). Node 18 or newer.

**Status:** the files were syntax-checked only. Cypress could not be installed in the environment where this example was written, so its two tests have not been run. The same flow was run with Playwright and pytest (see the other examples). If you find a problem, email support@assertinbox.com.

## Run it

```sh
npm install
export ASSERTINBOX_KEY=ai_...            # from https://assertinbox.com/start
export ASSERTINBOX_NAMESPACE=yournamespace
npx cypress run
```

`PRACTICE_URL` defaults to `https://assertinbox.com/practice`. Use `npx cypress open` to watch the tests in the browser.

## Files

- `cypress/e2e/signup.cy.js`: the two tests.
- `cypress.config.js`: registers the AssertInbox tasks and reads `PRACTICE_URL`.
- `cypress-assertinbox.cjs`: the AssertInbox tasks (a copy of https://assertinbox.com/sdk/cypress-assertinbox.cjs).
- `ci/github-actions.yml`: a GitHub Actions workflow, saved as `.github/workflows/e2e.yml`. Add `ASSERTINBOX_KEY` as a repository secret and `ASSERTINBOX_NAMESPACE` as a repository variable.

How it works

cypress.config.js registers the AssertInbox tasks with registerAssertInboxTasks(on). Tasks run in Cypress's Node process, so the key stays out of the browser. The task assertinbox:address returns a new tag and address on every call, for example yournamespace.code-m2x8k1-q7zt3a@assertinbox.com, so each test has its own inbox and tests never read each other's mail.

The test submits the sign-up form first and only then waits. assertinbox:waitForOtp long-polls the API for the newest message to that address and returns the extracted code, repeating the wait twice after a timeout. It is given a 90 second task timeout, because Cypress stops a task after 60 seconds unless told otherwise. assertinbox:waitForLink does the same for the confirmation link. The practice app's rules are fixed: the code works once for 15 minutes, the link works once for 24 hours, and only AssertInbox addresses are accepted. The messages are deleted by the service after 24 hours.

To adapt it, replace the steps in signUp() with your own form and keep the two task calls.

Related guides

Free beta, run by AI agents

This example was written by AI agents, and it has not been run: the files were syntax-checked only, as described at the top of this page. The GitHub Actions workflow has not been run in CI either.