Playwright OTP testing gets stuck at one step: your app sends an SMS code and the test has nowhere to read it from. You have two working options. Use your auth provider's fixed test numbers on every run, or, for a true end-to-end check, buy a real number inside the test, type it into your form, wait for the code over an API and hand the number back if no SMS arrives. This guide shows the second option as a Playwright fixture in TypeScript, with the timeout, parallel-worker and refund details most tutorials skip. It is the written companion to our Playwright OTP video walkthrough.
We run NumberOTP, so the real-number examples use our Node SDK (numberotp 0.1.1). The Playwright parts work the same with any source of codes. The code below type-checks against Playwright 1.65 and the SDK; it was not run against a live purchase for this post, so treat it as a starting point for your own app.
Where does the OTP come from in a Playwright test?
The code has to come from somewhere the test can read: a fixed value you configured, an inbox you can query, or a real phone number you can poll. Each source tests a different amount of the real flow, so most teams use two of them.
| Source of the code | What it exercises | Good for | Limits |
|---|---|---|---|
| Provider test numbers (fixed code) | Your UI and your verify call | Every commit, fast and free | No SMS is sent, so the carrier path and your SMS template are never tested |
| Mocked SMS sender | Your code up to the send call | Unit and integration tests | Nothing leaves your process |
| TOTP secret (authenticator apps) | Authenticator-app 2FA | Login tests where 2FA is TOTP, not SMS | Does not apply to SMS codes |
| Real number read over an API | The whole path: your app, your SMS gateway, the carrier, the message text | Release checks, nightly runs, debugging "users don't get the code" | Costs a little per run, takes seconds to minutes, needs a key in CI |
Fixed test numbers are the right default. Firebase, for example, lets you register fictional phone numbers with a fixed code for phone sign-in (up to 10 per project), and no real SMS is sent for them. The trade-off is in that last sentence: a test that never sends an SMS can't catch a broken template, a sender ID a carrier filters, or a country your SMS vendor stopped delivering to. Our guide to testing SMS OTP at every layer covers mocks and test numbers in more depth; the rest of this post is about the real-number run.
Step 1: give the SMS wait a timeout budget
Raise the timeout only for the test that waits for an SMS, and keep the code wait shorter than the test timeout. Playwright's default test timeout is 30 seconds, which is too short for a real message, and a test that times out mid-wait gives you a less useful error than one that fails on its own deadline.
Three clocks are running in this test, and they need to nest:
- Playwright test timeout: 30 seconds by default, per the Playwright timeouts reference. It covers the test body plus its
beforeEachhooks and fixture setup. Raise it for this test withtest.setTimeout(5 * 60_000)rather than for the whole suite (test.slow()triples it instead). Don't wrap the SMS wait inexpect.poll: assertion and poll timeouts default to 5 seconds and are separate from the test timeout. - Your code wait: the
timeoutyou pass towaitForCode. The SDK's default is 20 minutes, the full life of a number, which is far longer than you want a CI job to hang. Three minutes is a sensible ceiling for a release check. - The number's own window: on NumberOTP an activation is open for about 20 minutes. If no SMS arrives in that time it expires and the price goes back to your balance automatically.
The order that works: code wait (3 min) < test timeout (5 min) < number window (20 min). Then a slow SMS fails the test with a clear WaitTimeoutError, the fixture still has time to clean up, and the number is never billed for a code you didn't get.
Step 2: wrap the number in a Playwright fixture
Put the purchase and the cleanup in a test-scoped fixture, so every test that asks for a phone gets its own number and the number is released even when the test fails. Writing the buy and cancel inside each test body is how numbers leak: a failed assertion jumps past your cleanup line.
Install the two packages and set your key as an environment variable (NOTP_API_KEY), as the SDK setup guide describes:
npm i -D @playwright/test
npm i numberotp
Then create tests/fixtures.ts:
import { test as base } from '@playwright/test'
import { NumberOTP, type Duration } from 'numberotp'
const notp = new NumberOTP() // reads NOTP_API_KEY from the environment
type Phone = {
number: string
waitForCode: (timeout?: Duration) => Promise<string>
finish: () => Promise<void>
}
export const test = base.extend<{ phone: Phone }>({
phone: async ({}, use) => {
const n = await notp.activations.create({ service: 'ot', country: '187', max_price: 3 })
let finished = false
await use({
number: n.data.phoneNumber,
waitForCode: async (timeout = '3m') => {
const act = await notp.activations.waitForCode(n.data.id, { timeout })
if (!act.otp) throw new Error('SMS arrived but no code was found in it')
return act.otp
},
finish: async () => {
await notp.activations.finish(n.data.id)
finished = true
},
})
// Teardown: runs even when the test failed or timed out.
if (!finished) {
await notp.activations.cancel(n.data.id).catch(() => {
// Cancel opens two minutes after purchase. If it is refused here,
// the number still expires at the end of its window and is refunded.
})
}
},
})
export { expect } from '@playwright/test'
A few choices in that file are deliberate:
- Service
ot("any other"). Your own app is not a listed service, so you buy a number for the generic code.notp.services.search({ q: 'any other' })returns it if you want to look it up. - Country
187is the United States in our country codes. Use the country your users are in;notp.prices.get({ service: 'ot' })lists price and stock per country. max_priceis a ceiling, so a test can never buy above the amount you set. Current prices are on the pricing page.otpcan be null in the SDK's types (an SMS can arrive without a code the parser recognises), so the fixture fails loudly instead of typing "null" into your form.- The teardown cancel can be refused. Our refund policy allows a manual cancel from two minutes after purchase. A test that fails in its first two minutes can't cancel, which is fine: the number expires unused and the cost is credited back automatically.
Step 3: write the sign-up test
The test itself reads like a person signing up: type the number, ask for a code, read it, type it, check the next page. Everything about money and cleanup stays in the fixture.
import { test, expect } from './fixtures'
test('sign up once with a real SMS code', async ({ page, phone }) => {
test.setTimeout(5 * 60_000) // default is 30 s; the SMS wait needs more
await page.goto('/signup')
await page.getByLabel('Phone').fill(phone.number)
await page.getByRole('button', { name: 'Send code' }).click()
const code = await phone.waitForCode('3m')
await page.getByLabel('Code').fill(code)
await page.getByRole('button', { name: 'Verify' }).click()
await expect(page).toHaveURL(/welcome/)
await phone.finish()
await page.context().storageState({ path: 'playwright/.auth/user.json' })
})
Two things to check in your own app before the first run. First, the number format: the SDK returns the number as digits with the country code and no leading + (the API reference's example is 12025551234), so if your phone field expects a separate country picker or a leading +, adapt the fill step (our post on E.164 format errors in SMS verification lists the usual mismatches). Second, the locators: getByLabel and getByRole need real labels on your inputs and buttons, which also helps screen-reader users.
Step 4: pay for the SMS once, reuse the login everywhere
Only one test should go through the SMS step; every other test should start already signed in. Playwright supports this directly: a setup project signs in and saves the browser state, and the other projects load it, as described in Playwright's authentication guide.
import { defineConfig } from '@playwright/test'
export default defineConfig({
use: { baseURL: 'http://localhost:3000' },
projects: [
{ name: 'setup', testMatch: /auth\.setup\.ts/ },
{
name: 'e2e',
dependencies: ['setup'],
use: { storageState: 'playwright/.auth/user.json' },
},
],
})
Save the test from Step 3 as tests/auth.setup.ts. A suite of 200 tests then buys one number per run instead of 200, and a slow SMS delays the run once. Add playwright/.auth to .gitignore: the saved file holds live session cookies.
Parallel workers, retries and CI
Every test that needs a code needs its own number, and retries buy again. These are the two places where real-number tests surprise people on the first CI bill or the first flaky night.
- Parallel workers: Playwright runs test files in parallel workers. Because the fixture is test-scoped, each test gets its own number, so two workers never read each other's code. Never share one number across tests: the second test can pick up the first test's SMS.
- Test retries: with
retries: 2in CI, a failing SMS test can buy three numbers. The unused ones are cancelled or expire and are refunded, but if you want to see a real failure rather than a retried pass, addtest.describe.configure({ retries: 0 })to that file. - Network retries are a different thing: the SDK retries failed network calls,
429and5xxresponses on its own, and each purchase carries an idempotency key, so a retried request can't buy twice. That protects you from double purchases inside one call, not from Playwright re-running the whole test. - Keys in CI: store the key as a CI secret exposed as
NOTP_API_KEY, and create a key limited to theread,buyscope for test runners. Locally, keep it in a.envfile listed in.gitignore. - Many codes at once: waiting inside the test is simplest. If a nightly job checks several countries in parallel, the event stream or a signed webhook receiver scales better than one long poll per test; the article on rental numbers for SMS test pipelines covers longer-lived numbers for that kind of setup.
When the code doesn't arrive: what the failure tells you
A real-number test that fails is useful only if you can tell why. The SDK raises a small set of typed errors, and each one points to a different layer.
| Error | What happened | What to check |
|---|---|---|
WaitTimeoutError | Your 3-minute wait ended with the number still open | Did your app send at all? Check your SMS gateway's logs for that number. The fixture cancels the number. |
ActivationClosedError | The number expired or was cancelled before a code arrived; it was refunded | Usually a code wait longer than the window, or a cancel from elsewhere |
NotFoundError with NO_NUMBERS_AVAILABLE | No stock for that country right now | Try another country, or pick one with stock from prices.get |
InsufficientBalanceError | The test account is out of balance | Top up; a CI job failing on 402 is a billing alert, not a bug |
Assertion on /welcome/ fails after the code | The code reached the test but your app rejected it | Code expiry, a wrong code length, or a verify call that compares against a stale code |
The full list is on the error codes reference. If timeouts keep happening on one country while others pass, that is the finding the test exists to catch: something between your SMS vendor and that country's carriers is dropping the message, which a fixed test number would never show you.
When not to use a real number
Don't put a real-number test on every pull request. It is slower than a fixed test number, costs a little each time, and depends on a network you don't control. A pattern that works: fixed test numbers on every commit, the real-number setup test nightly and before releases, and one real-number run per country you send to before you launch there.
Use it only for your own app and accounts you control. Use it for your own accounts and follow each platform's terms; some platforms don't allow virtual numbers. Codes usually arrive, but delivery is never guaranteed, which is why the automatic refund and the cancel in teardown matter. If your sign-up form also has a captcha, our post on testing sign-up flows with captcha and SMS OTP covers that step.
How NumberOTP fits a Playwright suite
NumberOTP gives you real SIM-backed, non-VoIP numbers from three independent number pools on our own infrastructure, which matters because many apps reject VoIP numbers (more on that in what apps actually check about your number). For test code the parts that count are the tooling and the billing: official SDKs for Node/TypeScript, Python, Go and PHP, the notp CLI, an MCP server, an OpenAPI spec, webhooks and live events, idempotent purchases, pay per number by card or crypto with no subscription, and an automatic refund when no SMS arrives. You can try the calls in the API playground before writing any test code.
Frequently Asked Questions
How do I handle OTP in Playwright?
Read the code from a source the test can query, then type it like a user would. For fast runs, configure a fixed test number in your auth provider. For an end-to-end run, buy a real number in a fixture, fill it into your form, wait for the SMS over an API and type the returned code. Keep the code wait shorter than the test timeout.
What is Playwright's default test timeout?
Playwright's default test timeout is 30 seconds, and it covers fixture setup and beforeEach hooks as well as the test body. A real SMS can take longer than that, so raise the timeout only for the test that waits for a code, for example with test.setTimeout(5 * 60_000), and give the code wait itself a shorter limit so failures are clear.
Can Playwright read SMS messages from a phone?
Not by itself. Playwright drives browsers, so it has no access to a phone's messages. The test needs another way to get the code: a fixed code from your auth provider's test numbers, a mocked sender in your own backend, or a virtual number whose incoming SMS you can read through an API, which is the approach this guide uses.
How do I avoid entering an OTP in every Playwright test?
Sign in once in a setup project and save the browser state with storageState, then let every other project load that file. Only the setup test goes through the SMS step, so a large suite pays for one code per run and a slow message delays the run only once. Keep the saved file out of version control.
What happens to the cost if the SMS never arrives?
On NumberOTP an activation stays open for about 20 minutes. If no SMS arrives in that window, it expires and the price is credited back to your balance automatically. You can also cancel it yourself from two minutes after purchase, which is what the fixture's teardown does when a test fails without receiving a code.
Run your first real Playwright OTP test
Copy the fixture, point the sign-up test at your staging URL and run it once by hand before it goes into CI. Create a NumberOTP account and an API key, then follow the SDK guide for the Python, Go or PHP versions of the same calls.
Frequently Asked Questions
How do I handle OTP in Playwright?+
Read the code from a source the test can query, then type it like a user would. For fast runs, configure a fixed test number in your auth provider. For an end-to-end run, buy a real number in a fixture, fill it into your form, wait for the SMS over an API and type the returned code. Keep the code wait shorter than the test timeout.
What is Playwright's default test timeout?+
Playwright's default test timeout is 30 seconds, and it covers fixture setup and beforeEach hooks as well as the test body. A real SMS can take longer than that, so raise the timeout only for the test that waits for a code, for example with test.setTimeout(5 * 60_000), and give the code wait itself a shorter limit so failures are clear.
Can Playwright read SMS messages from a phone?+
Not by itself. Playwright drives browsers, so it has no access to a phone's messages. The test needs another way to get the code: a fixed code from your auth provider's test numbers, a mocked sender in your own backend, or a virtual number whose incoming SMS you can read through an API, which is the approach this guide uses.
How do I avoid entering an OTP in every Playwright test?+
Sign in once in a setup project and save the browser state with storageState, then let every other project load that file. Only the setup test goes through the SMS step, so a large suite pays for one code per run and a slow message delays the run only once. Keep the saved file out of version control.
What happens to the cost if the SMS never arrives?+
On NumberOTP an activation stays open for about 20 minutes. If no SMS arrives in that window, it expires and the price is credited back to your balance automatically. You can also cancel it yourself from two minutes after purchase, which is what the fixture's teardown does when a test fails without receiving a code.
Need a number right now? Get $0.10 in free credits — no card required.
Sign up free →Written by
Nanami
Nanami is a telecom and digital privacy specialist at NumberOTP with over 8 years of experience in SMS verification systems, virtual phone infrastructure, and online identity protection. He covers OTP security, number masking, developer APIs, and privacy-first verification workflows for businesses and developers worldwide.
Get your first OTP number free
$0.10 in credits on signup. No card required. Works for 800+ platforms.