# How to test SMS verification codes in automated tests

> How to test SMS OTP and phone verification end to end in Playwright, Cypress or any test runner: stub the provider, rent a Twilio number yourself, or use dedicated test numbers with a blocking wait-for-code API. Code, costs, parallelism and pitfalls.

Last updated 2026-12-03 · By the Humanless team at Ninety Nine Oranges · Canonical: https://usehumanless.com/guides/sms-verification-testing

> **Short answer:** For most tests, stub or bypass SMS in your app (provider test credentials, or fictional test numbers with fixed codes) so they are fast and free. For the few tests that must prove a real SMS arrives, give each test a **real phone number that your code can read**: either rent a number from Twilio and read its inbound messages through their API, or use a service with dedicated test numbers and a blocking wait call, such as Humanless (`channels: ["sms"]`, then `waitForCode`). Run as many SMS tests in parallel as you have numbers.

> **Use policy:** Test numbers are for verifying phone flows in apps you own or are authorized to test. Humanless numbers are receive-only and must not be used to register on or get past verification on third-party services. See the [Terms](/terms).

## Pick the right layer

| Approach | What it proves | Cost | Parallelism |
|---|---|---|---|
| Mock your SMS client in unit and integration tests | Your code calls the provider correctly | Free | Unlimited |
| Provider test mode or fictional numbers (e.g. Firebase Auth test phone numbers with fixed codes) | The UI flow works with a known code | Free | Unlimited |
| Your own Twilio number and reading inbound messages | A real SMS reaches a real number | Number rental plus per-message fees on Twilio's [pricing page](https://www.twilio.com/en-us/sms/pricing/us) | One test per number at a time |
| Hosted test numbers with a wait API (Humanless, Mailosaur, MailSlurp) | A real SMS arrives, and the code is extracted for you | Humanless: $5 per number per 30 days plus $0.10 per SMS, or Builder $49/mo with 1 number and 500 SMS | One test per number at a time |

A healthy suite has many tests at the first two layers and a handful of real-SMS tests (sign-up, login, phone change) at the last two.

## Option 1: Your own Twilio number

If you already use Twilio, buy a number that can receive SMS and read what it receives. The simplest version polls the Messages API for messages sent to that number after the test started:

```ts twilio-otp.ts
import twilio from "twilio";

const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

export async function latestSmsCode(to: string, after: Date, timeoutMs = 60_000): Promise<string> {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const [msg] = await client.messages.list({ to, dateSentAfter: after, limit: 1 });
    const code = msg?.body.match(/\b(\d{6})\b/)?.[1];
    if (code) return code;
    await new Promise((r) => setTimeout(r, 2_000));
  }
  throw new Error(`No SMS to ${to} within ${timeoutMs} ms`);
}
```

This works, but you own the polling interval, the regex, the number inventory and the parallelism problem. Two tests sharing a number will read each other's codes. For push instead of polling, configure the number's incoming-message webhook and forward messages to your test runner, which is more infrastructure.

## Option 2: Dedicated test numbers with a wait call (the Humanless way)

On a paid plan or with pay-as-you-go credits, your account gets **dedicated US numbers**. They are never shared with other customers, and they are quarantined before they are ever reassigned. An SMS identity leases one of your numbers for the test. `waitForCode` holds the request open and returns the code as soon as the SMS lands:

```ts phone-verify.spec.ts
import { expect, test } from "@playwright/test";
import { Humanless, withIdentity } from "./humanless"; // TypeScript SDK, one file: usehumanless.com/sdk/humanless.ts

const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! });

test("verify phone number by SMS", async ({ page }) => {
  await withIdentity(hl, { channels: ["sms"] }, async ({ identity_id, phone }) => {
    // phone is E.164, e.g. "+14155550192"
    await page.goto("http://localhost:3000/settings/phone");
    await page.getByLabel("Phone number").fill(phone!);
    await page.getByRole("button", { name: "Send code" }).click();
    const { code } = await hl.waitForCode({ identityId: identity_id, channel: "sms", timeout: 25 });
    await page.getByLabel("Code").fill(code);
    await page.getByRole("button", { name: "Verify" }).click();
    await expect(page.getByText("Phone verified")).toBeVisible();
  });
});
```

You can combine channels in one identity (`channels: ["email", "sms"]`) when sign-up asks for both. Then wait on each channel separately with `channel: "email"` and `channel: "sms"`.

Over plain HTTP it's the same two calls as email:

```bash curl
curl -s -X POST https://api.usehumanless.com/v1/identities \
  -H "Authorization: Bearer $HUMANLESS_API_KEY" -H "Content-Type: application/json" \
  -d '{"channels":["sms"]}' | tee identity.json
# -> {"identity_id":"...","phone":"+1415...","channels":["sms"], ...}
ID=$(jq -r .identity_id identity.json)

curl "https://api.usehumanless.com/v1/identities/$ID/wait?channel=sms&timeout=60" \
  -H "Authorization: Bearer $HUMANLESS_API_KEY"
# -> {"type":"otp","code":"700215","channel":"sms","sender":"+1...", ...}
```

### Parallelism = number of numbers

Each SMS identity holds one of your numbers until it is **deleted or expires** (default 1 hour). After that the number cools down for 30 seconds before the next identity can use it. So:

- Builder includes 1 number (SMS tests effectively run one at a time). Pro includes 5. Extra numbers are $5 per 30 days each.
- If every number is in use, `createIdentity` fails with **409 `all_numbers_busy`**. Delete identities you're done with (`withIdentity` does it for you), or add numbers.
- Always delete in `finally`, or use `withIdentity` or a fixture. A crashed test that leaks an identity holds a number for up to an hour.

## Pitfalls

- **Phone number format.** Humanless returns E.164 (`+14155550192`). If your form has a separate country dropdown, select the US and type the number without `+1`.
- **Line-type checks.** If your app rejects VoIP or non-mobile numbers (for example with a carrier lookup), allowlist your test numbers in the test environment. Otherwise your app may refuse to send.
- **US numbers only.** Humanless numbers are US numbers. If your app only sends to other countries, you need numbers there. Mailosaur and MailSlurp offer other countries (see the [comparison](/compare/mailosaur-alternative)).
- **Delivery isn't guaranteed by anyone.** Carriers filter application-to-person SMS. In the US, traffic sent from unregistered 10DLC numbers can be blocked, so check your sending setup with your SMS provider if codes never arrive.
- **Rate limits on your own app.** Real OTP endpoints usually throttle per number. Tests that reuse a number quickly may hit your own limiter.
- **Resend.** Take `const t = Date.now()` before clicking "Resend" and wait with `since: t` to get the new code.
- **Cost control.** On Humanless, SMS identities need a paid plan or credits. When included SMS run out and credits can't cover more, new SMS identities fail with **402 `sms_quota_exceeded`** (existing ones keep receiving). Fall back to email or TOTP in non-critical tests.

## FAQ

### How do I test SMS OTP in Playwright?

Get a phone number your test can read, enter it in the form, trigger the SMS, wait for the message without a fixed sleep, extract the code and fill it. With Humanless: `createIdentity({ channels: ["sms"] })` → fill `phone` → click send → `waitForCode({ identityId, channel: "sms" })` → fill `code`.

### Can I test SMS verification without paying for SMS?

Yes, at the UI-flow level. Mock your SMS client, or use your auth provider's test numbers with fixed codes. You only need real numbers to prove that a real SMS is delivered.

### Can I use a free temporary phone number website for tests?

Don't. Public "receive SMS online" numbers are shared with everyone, so your codes are visible to strangers. They are frequently blocked and can't be automated reliably. Use numbers dedicated to your account.

### Can Humanless send SMS or receive calls?

No. Numbers are receive-only SMS. Humanless never sends SMS.

### How many SMS tests can run in parallel?

One per dedicated number at a time. Builder includes 1 number, Pro includes 5, and you can add more at $5 per 30 days each. Delete identities as soon as the code arrives to free the number for the next test.

### What happens to my numbers if I downgrade?

A number your account gives up is quarantined for 30 days before anyone else can get it, so late messages never reach another customer. Remove released numbers from any test accounts that depend on them.

## Related guides

- [How to test email OTP and verification codes in Playwright](/guides/playwright-email-otp)
- [How to let an AI agent complete sign-up, login and 2FA on your own app](/guides/ai-agent-2fa)
- [Humanless vs Mailosaur vs MailSlurp vs Mailtrap](/compare/mailosaur-alternative)
