Why tasks and not cy.request
cy.request would work against the endpoint, but the key would have to reach the spec through Cypress.env(), and everything in Cypress.env() is readable from the browser and shows up in the command log and videos. Tasks run in the Node process that started Cypress, read the key from process.env, and return only the parts the test needs: the number and the code.
Tasks in cypress.config.js
# handler_api reference: https://otpwatch.com/cypress-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/key
SMS_API_KEY=// handler_api reference: https://otpwatch.com/cypress-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
const { defineConfig } = require("cypress");
const API = process.env.SMS_API_BASE_URL || "https://sim-aggregator.org/stubs/handler_api.php";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
const CANCEL_TRIES = 9;
const CANCEL_PAUSE_MS = 10000;
async function sms(action, params = {}) {
const q = new URLSearchParams({ action, api_key: process.env.SMS_API_KEY || "" });
for (const [k, v] of Object.entries(params)) if (v != null) q.set(k, String(v));
const res = await fetch(`${API}?${q}`, { signal: AbortSignal.timeout(30000) });
if (!res.ok) throw new Error(`HTTP ${res.status} on ${action}`);
return (await res.text()).trim();
}
module.exports = defineConfig({
taskTimeout: 120000, // smsRelease may retry a refused cancel for (CANCEL_TRIES - 1) × CANCEL_PAUSE_MS
e2e: {
baseUrl: process.env.BASE_URL || "http://localhost:3000",
retries: { runMode: 0, openMode: 0 },
setupNodeEvents(on) {
on("task", {
async smsOrder({ service = "tg", country = 16, maxPrice = 2 } = {}) {
const reply = await sms("getNumber", { service, country, maxPrice });
if (!reply.startsWith("ACCESS_NUMBER:")) throw new Error(`getNumber refused: ${reply}`);
const [, id, number] = reply.split(":");
return { id, e164: `+${number}` };
},
smsStatus(id) {
return sms("getStatus", { id });
},
async smsRelease({ id, gotCode }) {
if (gotCode) return sms("setStatus", { id, status: 6 });
for (let i = 0; i < CANCEL_TRIES; i++) {
const r = await sms("setStatus", { id, status: 8 });
if (r !== "EARLY_CANCEL_DENIED") return r;
if (i < CANCEL_TRIES - 1) await sleep(CANCEL_PAUSE_MS); // too early to cancel: repeat later
}
throw new Error(`cancel ${id}: still EARLY_CANCEL_DENIED after ${CANCEL_TRIES} tries; cancel it later`);
},
});
},
},
});The config file runs on the Node installed on the machine, so Node 18 or newer gives you fetch without a package. Every task returns a value (a task that resolves undefined fails the test), which is why smsRelease returns the reply string.
Polling in a command chain
A plain while loop does not work in Cypress: commands are queued, not executed in place. Recursion over cy.task does:
// handler_api reference: https://otpwatch.com/cypress-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
export function waitForCode(id, timeoutMs = 180000, startedAt = Date.now()) {
return cy.task("smsStatus", id, { log: false }).then((reply) => {
if (reply.startsWith("STATUS_OK:")) return reply.slice("STATUS_OK:".length);
if (!reply.startsWith("STATUS_WAIT")) throw new Error(`getStatus: ${reply}`);
if (Date.now() - startedAt > timeoutMs) throw new Error(`no SMS within ${timeoutMs} ms`);
return cy.wait(3000, { log: false }).then(() => waitForCode(id, timeoutMs, startedAt));
});
}{ log: false } keeps sixty identical lines out of the command log; the final .then with the code still shows up.
The spec
// handler_api reference: https://otpwatch.com/cypress-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
import { waitForCode } from "../support/sms";
describe("phone verification", { tags: "@sms" }, () => {
let activation = null;
let gotCode = false;
afterEach(() => {
if (activation) cy.task("smsRelease", { id: activation.id, gotCode });
activation = null;
gotCode = false;
});
it("verifies a new account with a real SMS", () => {
cy.visit("/signup");
cy.get("input[name=email]").type(`qa+${Date.now()}@example.com`);
cy.task("smsOrder", { service: "tg", country: 16, maxPrice: 2 }).then((a) => {
activation = a; // ordered only when the form is ready
cy.get("input[name=phone]").type(a.e164);
cy.contains("button", "Send code").click();
waitForCode(a.id).then((code) => {
gotCode = true;
cy.get("input[name=code]").type(code);
});
});
cy.contains("button", "Verify").click();
cy.contains("h1", "Welcome").should("be.visible");
});
});afterEach runs after a failed test too, which is the point: no order is left holding money until its window runs out. The tags option needs a grep plugin; without one, put SMS specs in their own folder and run them with --spec "cypress/e2e/sms/**".
Which service code
The order only receives SMS from the service it names. Pick the code that matches the sender in your flow (tg for a Telegram login step, go for a Google account link, and so on). The list is on service codes, the country ids on country ids.
Keep runs cheap and quiet
retries: 0for these specs. A retried test orders a second number.- Run SMS specs serially. Cypress runs one spec at a time per machine; on a parallel CI matrix, keep them on one machine.
- Each run costs the "from" price of the pair. The default here, Telegram in the United Kingdom, was $1.3798 on ;
maxPricestops the order if that changes a lot. - Running this on a schedule: CI recipe.