DEV Community

How to test SMS one-time-password login end to end

Disclosure: this post is written by JuicySMS, a service that rents real mobile numbers. We use it in the example below, but the approach works with any real phone number you can read messages from.

If your app logs people in with a code sent by SMS, that flow is probably the most important path in your product and the least tested one. Unit tests mock the SMS provider, staging uses the provider's test numbers, and the first time a real message travels over a real mobile network is when a real user signs up.

This post covers what a sandbox can't tell you, what to test, and how to automate the whole flow with a real number in a Playwright test.

What test numbers don't tell you

SMS providers offer test credentials and magic numbers. They prove your code calls the provider correctly. They don't prove that:

  • the message arrives. Mobile networks filter traffic, and routes go down without your code changing.
  • the sender name survives. An alphanumeric sender ID can be replaced by a random number in some countries.
  • the text fits. One emoji or accented character switches the encoding, and a 140-character message becomes two.
  • the timing works. If codes take 40 seconds to arrive and expire after 60, users will hit "resend" and get the wrong code.
  • number parsing holds up. +44 7…, 07… and 0044 7… are the same number. Is your input field sure?

A checklist worth automating

  • A code arrives on a real number in every country you send to.
  • The text, sender and language match your template.
  • The code in the message logs you in; a wrong code doesn't.
  • An expired code is refused, and "resend" invalidates the old one.
  • Rate limits and resend limits behave as designed.
  • The same number typed in three different formats reaches the same account.

Getting a real number your test can read

You need a phone number that receives every SMS sent to it, and a way for code to read those messages. Options:

  • a physical phone with a SIM and some forwarding app (works, but someone has to keep it charged and topped up);
  • a device farm with real SIMs (great, usually expensive);
  • a rented mobile number with an API. We'll use the third.

A JuicySMS rental gives you a UK (+44) or Dutch (+31) mobile number for a month or longer that receives every SMS from any sender, and an API to read them. You can rent one in the dashboard or with one request.

Every request authenticates with the API key from your account page:

curl -X POST https://juicysms.com/api/v2/rentals \
  -H "Authorization: Bearer $JUICYSMS_KEY" \
  -H "Content-Type: application/json" \
  -d '{"country": "UK", "package": "1m", "auto_renew": false}'

The response includes the rental id and its phone_number. Store both as CI secrets and reuse the same number in every run.

The Playwright test

import { test, expect } from '@playwright/test';
const API = 'https://juicysms.com/api/v2';
const headers = { Authorization: `Bearer ${process.env.JUICYSMS_KEY}` };

async function waitForCode(rentalId: string, sentAfter: Date, timeoutMs = 120_000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const res = await fetch(`${API}/rentals/${rentalId}/messages`, { headers });
    const { data } = await res.json();
    const fresh = data.find((m: any) => new Date(m.received_at) > sentAfter && m.code);
    if (fresh) return fresh;
    await new Promise((r) => setTimeout(r, 5_000));
  }
  throw new Error('No SMS arrived in time');
}

test('SMS login works end to end', async ({ page }) => {
  const sentAfter = new Date();
  await page.goto('https://staging.example.com/login');
  await page.getByLabel('Phone number').fill(process.env.TEST_PHONE_NUMBER!);
  await page.getByRole('button', { name: 'Send code' }).click();
  const message = await waitForCode(process.env.JUICYSMS_RENTAL_ID!, sentAfter);
  expect(message.text).toContain('Your login code');
  await page.getByLabel('Code').fill(message.code);
  await page.getByRole('button', { name: 'Log in' }).click();
  await expect(page.getByText('Welcome back')).toBeVisible();
});

Each message comes back with the sender, the full text, received_at and a code field with the digits found in it. Assert on all of them: a changed sender or a broken template is exactly the kind of regression this test exists to catch.

Tips

  • Poll every few seconds, not in a tight loop, and fail with a clear timeout.
  • Log the delivery time of every run. A sudden jump usually means a route problem at your SMS provider, and you'll see it before your users do.
  • Run it nightly, not only on release. Delivery breaks without any deploy.
  • One number per country you send to. A UK and a Dutch number already exercise international formatting and two different networks.
  • Keep test numbers out of your real user data, or clean them up after the run.

If you have a different setup for testing SMS flows, especially on real devices, I'd like to hear how you do it in the comments.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.