Disclosure: I work with HeroSMS, the virtual number provider used in the examples. Written with AI tools; code and endpoints checked against the HeroSMS API reference and Twilio's docs.
Search for Twilio Verify test numbers and you'll land on the magic numbers Twilio documents for its test credentials, such as +15005550006. They won't help with Verify: test credentials work only with buying phone numbers, Messages, Calls, and Lookup; requests to anything else return 403 Forbidden. To prove that your Verify Service delivers a code and that Verify accepts it, you need a real SMS to a real number. This post builds that test in TypeScript with Vitest and a nightly GitHub Actions job.
Are there Twilio Verify test numbers?
Not for SMS. The closest options all fall short:
- Test credentials don't cover Verify. Twilio's testing guide (August 2025) says so: "Twilio's test credentials are not compatible with the Verify API." It adds that Twilio doesn't lift rate limits for testing and that there's no free sandbox, because carrier fees apply to every message.
- Trial accounts send codes only to verified numbers (up to five per account). Fine for your own phone, not for CI that needs a fresh number.
- The SNA Live Test Number is for Silent Network Auth with your own mobile number, not for SMS.
So split the work:
| Layer | How | What it proves | When |
|---|---|---|---|
| Unit | Mock your own wrapper around the Verify SDK | Your retry, error, and lockout logic | Every push |
| End-to-end | Rent a real number, read its SMS via an API | The SMS reaches a number in the target country; the real code is approved, a wrong one isn't | Nightly and before releases |
The end-to-end test catches what mocks can't:
- Geo Permissions. Verifications to a country you've disabled in Verify Geo Permissions are blocked.
- Fraud Guard. Fraud Guard blocks SMS it flags as suspicious and logs error 60410; Twilio says it can flag legitimate users, too.
Setup
Run npm install twilio and npm install -D vitest. Vitest 5 runs on Node 22 (22.12+), 24, or 26+. Then set five environment variables: TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN from an upgraded (non-trial) account, TWILIO_VERIFY_SERVICE_SID for the Verify Service your staging app uses, HEROSMS_API_KEY, and HEROSMS_COUNTRY (16 = United Kingdom, 187 = USA). An optional HEROSMS_MAX_PRICE caps the price per number. Configure the Verify Service like production (template, code length, Fraud Guard level), or the test proves less than you think.
Rent the number and read the SMS
The examples use HeroSMS, the provider I work with. Its REST API takes an Authorization: ApiKey <key> header and returns errors as JSON with title and details fields. Each purchase is an activation: one number for one service in one country. The service code is ot, listed as "Any other" in the catalog. Run the test once by hand before you schedule it.
| Step | Endpoint |
|---|---|
| Rent a number | POST /api/v1/activations |
| Read the latest SMS | GET /api/v1/activations/{id}/otp/last |
| SMS received: finish the activation | POST /api/v1/activations/{id}/finish |
| No SMS: cancel for a refund | DELETE /api/v1/activations/{id} |
// herosms.ts: one rented number per test
const API = "https://hero-sms.com/api/v1";
export class HeroSmsError extends Error {
constructor(public status: number, public title: string, details: string) {
super(`HeroSMS HTTP ${status} ${title}: ${details}`);
}
}
async function call(method: string, path: string, body?: object): Promise<any> {
const res = await fetch(API + path, {
method,
headers: { Authorization: `ApiKey ${process.env.HEROSMS_API_KEY}`, "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(15_000),
});
const text = await res.text();
let json: any = null;
try { json = JSON.parse(text); } catch {} // empty (204) or HTML reply
if (!res.ok) throw new HeroSmsError(res.status, json?.title ?? "", json?.details ?? text.slice(0, 200));
return json;
}
export async function rentNumber(country: number, maxPrice?: number) {
const res = await call("POST", "/activations", {
service: "ot", // "Any other"
country,
amount: 1,
verificationType: "sms",
...(maxPrice ? { maxPrice } : {}),
});
const a = res?.data?.[0];
if (!a) throw new Error("HeroSMS: empty purchase reply");
return { id: a.id as number, phone: `+${a.phone}` }; // phone comes without "+"
}
const CLOSED = ["ACTIVATION_NOT_ACTIVE", "CANCELED", "FINISHED", "REFUNDED"];
export async function waitForSms(id: number, timeoutMs = 240_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const otp = (await call("GET", `/activations/${id}/otp/last`))?.data;
if (otp?.smsCode || otp?.smsText) return { code: otp.smsCode as string | null, text: otp.smsText ?? "" };
} catch (e) {
// keep polling on network errors, 5xx, 429, 400, and 404; stop on other errors or a closed activation
const fatal = e instanceof HeroSmsError && e.status < 500 && ![400, 404, 429].includes(e.status);
if (fatal || (e instanceof HeroSmsError && CLOSED.includes(e.title))) throw e;
}
await new Promise((r) => setTimeout(r, 5_000));
}
return null;
}
export async function release(id: number, gotSms: boolean) {
try {
if (gotSms) await call("POST", `/activations/${id}/finish`); // no refund
else await call("DELETE", `/activations/${id}`); // cancel and refund
} catch (e) {
console.warn(`HeroSMS activation ${id} not closed: ${(e as Error).message}`);
}
}
Easy to miss:
smsCode(the code HeroSMS extracted) andsmsTextcan both be null. The poll reads 400 and 404 as "not yet" and retries network errors, 5xx, and 429, but stops on the closed-activationtitlevalues from the documentation's examples. Side effect: a wrongidlooks like a timeout.- The 5-second interval is my choice. HeroSMS can also POST each SMS to an HTTPS webhook (
sms-incoming) if your CI can expose one. - HeroSMS's documentation shows a cancel refused within the first 2 minutes (
EARLY_CANCEL_DENIED).release()only logs a failed cancel, so the test's own error stays visible. HeroSMS says that if no code arrives within the activation window of up to 20 minutes, the charge is refunded to your balance automatically.
For a similar Node loop inside Cypress, see Cypress SMS OTP Testing.
The test: start, wait, check twice
// verify.e2e.test.ts: sends a real SMS
import twilio from "twilio";
import { describe, expect, test } from "vitest";
import { release, rentNumber, waitForSms } from "./herosms";
const env = process.env;
const NEEDED = ["HEROSMS_API_KEY", "TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN", "TWILIO_VERIFY_SERVICE_SID"];
const ready = NEEDED.every((k) => env[k]);
if (env.VERIFY_E2E && !ready) throw new Error("E2E secrets missing");
describe.skipIf(!ready)("Twilio Verify, real SMS", () => {
test("approves the real code, rejects a wrong one", { timeout: 360_000 }, async () => {
const verify = twilio(env.TWILIO_ACCOUNT_SID, env.TWILIO_AUTH_TOKEN).verify.v2.services(
env.TWILIO_VERIFY_SERVICE_SID!,
);
const country = Number(env.HEROSMS_COUNTRY ?? "16");
const num = await rentNumber(country, Number(env.HEROSMS_MAX_PRICE) || undefined);
let gotSms = false;
let openSid: string | undefined;
try {
openSid = (await verify.verifications.create({ to: num.phone, channel: "sms" })).sid;
const sms = await waitForSms(num.id);
expect(sms, "no SMS within 4 minutes").not.toBeNull();
gotSms = true;
const code = sms!.code || sms!.text.match(/\b\d{4,10}\b/)?.[0];
if (!code || !/^\d{4,10}$/.test(code)) throw new Error("no numeric code in the SMS");
const wrong = code.slice(0, -1) + ((Number(code.at(-1)) + 1) % 10); // same length
const rejected = await verify.verificationChecks.create({ to: num.phone, code: wrong });
expect(rejected.status).not.toBe("approved");
const approved = await verify.verificationChecks.create({ to: num.phone, code });
expect(approved.status).toBe("approved");
openSid = undefined; // Twilio deletes approved verifications
} finally {
if (openSid) await verify.verifications(openSid).update({ status: "canceled" }).catch(() => {});
await release(num.id, gotSms);
}
});
});
What each part does:
describe.skipIfskips the suite when a secret is missing, so runs without secrets neither fail nor spend money. In the nightly job (VERIFY_E2E=1), the file throws instead, so a green nightly run always means a real code was checked.- The number is rented before Verify sends anything. If
verifications.createthrows, Vitest shows Twilio's message, and the SDK'sRestExceptionalso carries the numeric errorcode. - If
smsCodeis empty, the regex takes the first 4–10 digit number in the text, so keep digits out of your Verify Service's friendly name. - The wrong code has the same length, so it tests the comparison, not input validation. It uses one of five check attempts; once all five are used, Twilio returns error 60202.
- Twilio deletes a verification once it's approved, expired (after 10 minutes), or out of check attempts; checking it again returns 404. If the test fails before approval,
finallycancels the verification; Twilio's guide lists canceling as one way to avoid error 60203 (too many sends to one number within 10 minutes). A fresh number per run avoids it too. - The 6-minute test timeout covers the 4-minute poll plus the API calls around it at normal latency.
If your backend wraps Verify, swap verifications.create and the two checks for requests to your own "send code" and "verify code" endpoints, and drop the cancel, since you won't have the verification SID.
Run it nightly in GitHub Actions
name: twilio-verify-e2e
on:
schedule:
- cron: "30 3 * * *"
workflow_dispatch:
concurrency: twilio-verify-e2e
jobs:
e2e:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
- run: npm ci
- run: npx vitest run verify.e2e.test.ts
env:
TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }}
TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }}
TWILIO_VERIFY_SERVICE_SID: ${{ secrets.TWILIO_VERIFY_SERVICE_SID }}
HEROSMS_API_KEY: ${{ secrets.HEROSMS_API_KEY }}
HEROSMS_COUNTRY: "16"
VERIFY_E2E: "1"
Save it as .github/workflows/verify-e2e.yml. It runs daily at about 03:30 UTC (GitHub can delay scheduled runs) or manually from the Actions tab (workflow_dispatch), and concurrency keeps two runs from overlapping. npm ci needs a committed package-lock.json. Run the job on a schedule and before releases, not on every push, since each run pays for a number and a Verify SMS.
Twilio Verify errors: 60202, 60203, 60410
| Symptom | Likely cause |
|---|---|
60203 when starting |
Repeated sends to the same number within 10 minutes without a completed check |
60202 when checking |
All five check attempts used (only if you retry checks) |
404 when checking |
The verification was already approved, expired, or out of attempts |
No SMS, 60410 in Twilio's error logs |
Fraud Guard blocked the message |
| Verifications to the test country are blocked | Geo Permissions block that country |
| Can't send to the number at all | A trial account, which sends only to verified numbers |
| "no SMS within 4 minutes", no Twilio error | A slow route, a number that didn't receive it, or HeroSMS unreachable (errors are retried); rerun with a new number |
| "not closed" warning after a quick failure | The cancel came too early; HeroSMS says an activation with no code is refunded when its window ends |
If you add logging, never print the code. Print the activation id and the verification sid: they're what you'll look up in the HeroSMS activation history and in Twilio's Verify logs.
Checklist
- A non-trial Twilio account and the Verify Service your staging app uses.
- Geo Permissions that allow the test country, and a known Fraud Guard level.
- A fresh number per run, rented before Verify sends the code.
- A deadline on the poll and a clear failure message.
- A wrong code of the same length, then the right one.
- A
finallythat cancels an open verification, then finishes or cancels the activation. - Credentials in CI secrets only; no codes or SMS text in logs.
Use rented numbers only on apps you own or are authorized to test, and don't tie them to accounts you'll need later: a number is yours only while its activation lasts.
To try it, create a HeroSMS API key, pick a test country, and add the four secrets from the workflow to your repository.
About the author
- I work with HeroSMS, a virtual phone number service, and write practical guides on testing SMS/OTP flows: Python scripts, Playwright end-to-end tests, webhooks and CI pipelines. I focus on code you can actually run and on the parts of phone verification that tend to break.
Comments
Join the discussionNo comments yet. Be the first to comment.