How to test SMS OTP codes in Playwright
Playwright can fill your phone verification form, but it can't read a text message. With a real test number and a small API helper, it can.
What you need
- A QuickInbox paid plan with its included US number (claim it on the SMS page).
- An API key in the
QI_KEYenvironment variable. - Node 18 or newer (for the built-in
fetch).
Step 1: the SMS helper
// sms.js - read texts sent to your QuickInbox test number (Node 18+)
const BASE = 'https://business.quickinbox.net';
const auth = { headers: { 'X-API-Key': process.env.QI_KEY } };
export async function getNumber() {
const res = await fetch(`${BASE}/api/business/sms/numbers`, auth);
const { numbers } = await res.json();
if (!numbers?.length) throw new Error('No SMS number on this account yet');
return numbers[0]; // { id, phone_number, ... }
}
async function listMessages(numberId) {
const res = await fetch(`${BASE}/api/business/sms/numbers/${numberId}/messages`, auth);
if (!res.ok) throw new Error(`SMS API ${res.status}`);
return (await res.json()).messages; // newest first
}
// Remember which texts already exist, so the test only reads new ones.
export async function snapshot(numberId) {
return new Set((await listMessages(numberId)).map((m) => m.id));
}
export async function waitForCode(numberId, seen, { timeoutMs = 90_000, pattern = /\b(\d{4,8})\b/ } = {}) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const fresh = (await listMessages(numberId)).filter((m) => !seen.has(m.id));
const hit = fresh.find((m) => pattern.test(m.body));
if (hit) return hit.body.match(pattern)[1];
await new Promise((r) => setTimeout(r, 3000));
}
throw new Error('No new SMS code arrived in time');
}The snapshot step matters: a test number keeps its older texts, so the test records which messages already exist before it asks for a code, then waits only for a new one. That way an old code can never pass the test by accident.
Step 2: the test
// tests/phone-verify.spec.ts
import { test, expect } from '@playwright/test';
import { getNumber, snapshot, waitForCode } from './sms.js';
test('user can verify their phone number', async ({ page }) => {
test.setTimeout(120_000); // texts can take a few seconds
const number = await getNumber();
const seen = await snapshot(number.id);
await page.goto('/settings/phone');
await page.getByLabel('Phone number').fill(number.phone_number);
await page.getByRole('button', { name: 'Send code' }).click();
const code = await waitForCode(number.id, seen);
await page.getByLabel('Verification code').fill(code);
await page.getByRole('button', { name: 'Verify' }).click();
await expect(page.getByText('Phone number verified')).toBeVisible();
});Change the labels to match your app. If your form wants the number without +1, strip it first.
Running SMS tests in parallel
All workers share one number unless you buy more, so a parallel run could read another test's code. Either put SMS tests in their own project that runs with one worker, or give each worker its own number:
// playwright.config.ts
projects: [
{ name: 'sms', testMatch: /.*phone.*\.spec\.ts/, fullyParallel: false },
{ name: 'rest', testIgnore: /.*phone.*\.spec\.ts/ },
],and run with npx playwright test --project=sms --workers=1 for that part.
Tips
- Give the wait 60 to 90 seconds. Most texts arrive in seconds, but carriers have slow moments.
- If your texts contain other numbers, pass a tighter
pattern, such as/code is (\d{6})/. - Test the email version too: email verification in Playwright.
Related guides
- How to test SMS OTP codes in Cypress
- How to test SMS 2FA in Selenium with Python
- How to test Twilio Verify and OTP flows end to end
- How to test phone verification in mobile apps with Appium
- SMS testing overview
Get a test number: every paid QuickInbox plan includes a real US phone number and a monthly SMS allowance, with plans from $9 a month. Extra packs start at $5 a month. See SMS testing and pricing.