# Playwright: SMS verification tests with a real number

> A Playwright fixture that orders a number at the moment your form is ready to send the code, waits for the SMS, and finishes or cancels the order in teardown whether the test passed or not. Tag the tests, give them their own project, and they stop touching the rest of the suite.

Source: https://otpwatch.com/playwright-otp-testing
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## Which service code goes in the order

An order receives SMS from the service named in it, and only from that service: the platform matches each incoming message to the order for the sender. So the code must match whoever sends the SMS in your flow. Typical cases in a Playwright suite:

- your product has a "log in with Telegram" or WhatsApp step, and the test account needs a real number: `tg`, `wa`;
- your onboarding links a Google or Discord account: `go`, `ds`;
- you test a bot or integration that lives on one of these platforms.

The common codes are on the [service codes](https://otpwatch.com/service-codes.md) page and `getServicesList` returns all of them. If your own backend sends the SMS under its own sender name, ask SimAggregator support which code to use before you script it.

## The fixture

```env title=".env.example"
# handler_api reference: https://otpwatch.com/playwright-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```ts title="tests/sms-fixture.ts"
// handler_api reference: https://otpwatch.com/playwright-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
import { test as base } from "@playwright/test";

const API = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const sleep = (ms: number) => 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 = 10_000;

async function sms(action: string, params: Record<string, string | number> = {}): Promise<string> {
  const q = new URLSearchParams({ action, api_key: process.env.SMS_API_KEY ?? "" });
  for (const [k, v] of Object.entries(params)) q.set(k, String(v));
  const res = await fetch(`${API}?${q}`, { signal: AbortSignal.timeout(30_000) });
  if (!res.ok) throw new Error(`HTTP ${res.status} on ${action}`);
  return (await res.text()).trim();
}

export type Phone = { id: string; e164: string; waitCode(timeoutMs?: number): Promise<string>; anotherCode(): Promise<void> };
type Sms = { order(opts?: { service?: string; country?: number; maxPrice?: number }): Promise<Phone> };

export const test = base.extend<{ sms: Sms }>({
  sms: [
    async ({}, use, testInfo) => {
      const opened: { id: string; code?: string }[] = [];
      await use({
        async order({ service = process.env.SMS_SERVICE ?? "tg", country = Number(process.env.SMS_COUNTRY ?? 16), maxPrice = Number(process.env.SMS_MAX_PRICE ?? 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(":");
          const rec: { id: string; code?: string } = { id };
          opened.push(rec);
          return {
            id,
            e164: `+${number}`,
            async waitCode(timeoutMs = 180_000) {
              const deadline = Date.now() + timeoutMs;
              while (Date.now() < deadline) {
                const s = await sms("getStatus", { id });
                if (s.startsWith("STATUS_OK:")) return (rec.code = s.slice("STATUS_OK:".length));
                if (!s.startsWith("STATUS_WAIT")) throw new Error(`getStatus: ${s}`);
                await sleep(3_000);
              }
              throw new Error(`no SMS on ${number} within ${timeoutMs} ms`);
            },
            async anotherCode() {
              await sms("setStatus", { id, status: 3 });
              rec.code = undefined;
            },
          };
        },
      });
      // Teardown runs after every test, passed or failed.
      const stuck: string[] = [];
      for (const rec of opened) {
        let reply = rec.code ? await sms("setStatus", { id: rec.id, status: 6 }) : "";
        for (let i = 0; !rec.code && i < CANCEL_TRIES; i++) {
          reply = await sms("setStatus", { id: rec.id, status: 8 });
          if (reply !== "EARLY_CANCEL_DENIED") break;
          if (i < CANCEL_TRIES - 1) await sleep(CANCEL_PAUSE_MS); // too early to cancel: repeat later
        }
        testInfo.annotations.push({ type: "sms", description: `${rec.id}: ${reply}` });
        if (reply === "EARLY_CANCEL_DENIED") stuck.push(rec.id);
      }
      if (stuck.length) throw new Error(`cancel still EARLY_CANCEL_DENIED after ${CANCEL_TRIES} tries: ${stuck.join(", ")}`);
    },
    { timeout: 150_000 }, // own timeout: a refused cancel is retried up to CANCEL_TRIES times
  ],
});
export { expect } from "@playwright/test";
```

Two decisions in there matter more than the code:

- **The number is ordered inside the test, not in fixture setup.** The activation window starts at `getNumber`. Ordering in `beforeAll` while containers boot burns that window and, if the test is skipped, leaves an order that never gets an SMS.
- **Teardown has its own timeout.** `setStatus` 8 can answer `EARLY_CANCEL_DENIED`: too early to cancel, repeat the request later. The docs give no time, so teardown repeats the cancel with a pause and fails with the stuck ids after the last try. That wait should not eat the test's own budget.

## The test

```ts title="tests/signup.spec.ts"
// handler_api reference: https://otpwatch.com/playwright-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
import { test, expect } from "./sms-fixture";

test("new user verifies a phone number", { tag: "@sms" }, async ({ page, sms }) => {
  test.setTimeout(240_000);
  await page.goto("/signup");
  await page.getByLabel("Email").fill(`qa+${Date.now()}@example.com`);

  const phone = await sms.order();                 // only now: the form is ready to send
  await page.getByLabel("Phone number").fill(phone.e164);
  await page.getByRole("button", { name: "Send code" }).click();

  const code = await phone.waitCode();
  await page.getByLabel("Verification code").fill(code);
  await page.getByRole("button", { name: "Verify" }).click();
  await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
});
```

If your form splits the code into six inputs, type it instead of filling: `await page.getByLabel("Verification code").first().pressSequentially(code)`, which also exercises the auto-advance logic.

## Config: a separate project with no retries

```ts title="playwright.config.ts"
// handler_api reference: https://otpwatch.com/playwright-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
import { defineConfig } from "@playwright/test";

export default defineConfig({
  use: { baseURL: process.env.BASE_URL ?? "http://localhost:3000" },
  projects: [
    { name: "ui", grepInvert: /@sms/ },
    { name: "sms", grep: /@sms/, retries: 0 },
  ],
});
```

```bash title="run"
# handler_api reference: https://otpwatch.com/playwright-otp-testing
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
npx playwright test --project=ui
npx playwright test --project=sms --workers=2
```

- **No retries for paid tests.** A retry runs the test from scratch and orders a second number. If a flaky step needs a second chance, retry that step inside the test and reuse `phone`, or call `phone.anotherCode()` for a new SMS on the same number.
- **Few workers.** Each worker holding a number takes one of the account's simultaneous-order slots, and each polling loop spends requests from the key's 600 per minute. Two or three workers cover most suites.

## Safety net: cancel leftovers after the run

If the runner is killed, teardown never runs. A global teardown can find anything this key left open:

```ts title="tests/global-teardown.ts"
// handler_api reference: https://otpwatch.com/playwright-otp-testing
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
// playwright.config.ts: globalTeardown: "./tests/global-teardown.ts"
export default async function globalTeardown() {
  const API = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
  const key = process.env.SMS_API_KEY;
  if (!key) return;
  const body = await (await fetch(`${API}?action=getCurrentActivationsList&api_key=${key}`)).text();
  if (!body.trim().startsWith("[")) return;
  for (const a of JSON.parse(body) as { numberid: number; status: number }[]) {
    if (a.status !== 0) continue; // 0 = still waiting for a code
    const r = await (await fetch(`${API}?action=setStatus&api_key=${key}&id=${a.numberid}&status=8`)).text();
    console.log(`activation ${a.numberid}: ${r}`);
  }
}
```

Use a key that only this suite uses. `getCurrentActivationsList` returns the orders of the key, and on a shared key you would cancel a colleague's manual order.

## Budget per run

The price of one test is the "from" price of its pair. For the default Telegram and United Kingdom pair it was $1.3798 on 24 Nov 2026. Set `SMS_MAX_PRICE` a little above that and the order is refused instead of silently costing more when prices move; [price control](https://otpwatch.com/price-control.md) explains the refusals.
