OTP login is one of the hardest features to test. The code goes to a real phone, the provider costs money per message, rate limits get in the way, and your CI server can't open WhatsApp. So many teams skip tests, or test only the happy path by hand.

This tutorial shows a setup that works: keep the provider behind a small interface, test your logic with a fake provider, run a few end-to-end tests the same way, and keep one tiny smoke test for the real provider. We'll write it in TypeScript with Vitest (Jest works the same way), using the Authly SDK as the real provider. I'm the maker of Authly, but the pattern works with any provider.

The strategy: a test pyramid for OTP

![The OTP test pyramid]

  • Unit tests (hundreds): your OTP logic with a fake provider. Fast, free, no network.
  • End-to-end tests (dozens): the real app and real browser, but with the fake provider switched on by an environment variable.
  • Smoke test (one per release): a single call to the real provider to prove the integration still works.

Step 1: put the provider behind an interface

The trick is that your app code never imports the SDK directly. Create src/otp/provider.ts:

export interface OtpProvider { send(phone: string): Promise<{ otpId: string }>; verify(otpId: string, code: string): Promise<boolean>; } 

The real implementation wraps the Authly SDK, src/otp/authlyProvider.ts:

import Authly from "authly-otp"; import type { OtpProvider } from "./provider"; export class AuthlyProvider implements OtpProvider { private client: Authly; constructor(apiKey: string) { this.client = new Authly(apiKey); } async send(phone: string) { const { otpId } = await this.client.otp.send({ to: phone, channel: "whatsapp", fallbackChannel: "telegram", lang: "en", }); return { otpId }; } async verify(otpId: string, code: string) { try { const result = await this.client.otp.verify({ otpId, code }); return result.verified === true; } catch { return false; // treat provider errors on verify as "not verified" } } } 

Step 2: the logic you actually want to test

Your rules (cooldowns, expiry, attempt limits) belong in a service that talks only to the interface. src/otp/service.ts:

import type { OtpProvider } from "./provider"; export type OtpErrorCode = | "INVALID_PHONE" | "COOLDOWN" | "PROVIDER_ERROR" | "NO_PENDING_CODE" | "EXPIRED" | "TOO_MANY_ATTEMPTS"; export class OtpError extends Error { constructor(public code: OtpErrorCode) { super(code); } } type Pending = { otpId: string; sentAt: number; expiresAt: number; attempts: number }; const E164 = /^\+[1-9]\d{7,14}$/; export class OtpService { private pending = new Map<string, Pending>(); private now: () => number; private ttlMs: number; private cooldownMs: number; private maxAttempts: number; constructor( private provider: OtpProvider, opts: { now?: () => number; ttlMs?: number; cooldownMs?: number; maxAttempts?: number } = {} ) { this.now = opts.now ?? Date.now; this.ttlMs = opts.ttlMs ?? 5 * 60_000; this.cooldownMs = opts.cooldownMs ?? 60_000; this.maxAttempts = opts.maxAttempts ?? 5; } async start(phone: string) { if (!E164.test(phone)) throw new OtpError("INVALID_PHONE"); const existing = this.pending.get(phone); if (existing && this.now() - existing.sentAt < this.cooldownMs) { throw new OtpError("COOLDOWN"); } let otpId: string; try { ({ otpId } = await this.provider.send(phone)); } catch { throw new OtpError("PROVIDER_ERROR"); // cooldown is NOT consumed on failure } this.pending.set(phone, { otpId, sentAt: this.now(), expiresAt: this.now() + this.ttlMs, attempts: 0, }); } async check(phone: string, code: string): Promise<boolean> { const rec = this.pending.get(phone); if (!rec) throw new OtpError("NO_PENDING_CODE"); if (this.now() > rec.expiresAt) { this.pending.delete(phone); throw new OtpError("EXPIRED"); } if (rec.attempts >= this.maxAttempts) { this.pending.delete(phone); throw new OtpError("TOO_MANY_ATTEMPTS"); } rec.attempts += 1; const ok = await this.provider.verify(rec.otpId, code); if (ok) this.pending.delete(phone); // single use return ok; } } 

Notice the injectable now function. It lets tests control time without fake timers.

Step 3: a fake provider

src/otp/fakeProvider.ts behaves like a provider but is fully predictable, with a fixed code and a switch for simulating outages:

import type { OtpProvider } from "./provider"; export class FakeOtpProvider implements OtpProvider { static CODE = "123456"; sent: string[] = []; failNext = false; private codes = new Map<string, string>(); private phones = new Map<string, string>(); async send(phone: string) { if (this.failNext) { this.failNext = false; throw new Error("provider unavailable"); } const otpId = `otp_${this.sent.length + 1}`; this.sent.push(phone); this.codes.set(otpId, FakeOtpProvider.CODE); this.phones.set(phone, otpId); return { otpId }; } async verify(otpId: string, code: string) { return this.codes.get(otpId) === code; } lastCodeFor(phone: string) { const otpId = this.phones.get(phone); return otpId ? this.codes.get(otpId) : undefined; } } 

Step 4: unit tests with Vitest

npm install -D vitest 

src/otp/service.test.ts:

import { describe, it, expect, beforeEach } from "vitest"; import { OtpService, OtpError } from "./service"; import { FakeOtpProvider } from "./fakeProvider"; const PHONE = "+14155552671"; describe("OtpService", () => { let provider: FakeOtpProvider; let service: OtpService; let clock: number; beforeEach(() => { provider = new FakeOtpProvider(); clock = 0; service = new OtpService(provider, { now: () => clock }); }); it("verifies the right code", async () => { await service.start(PHONE); expect(await service.check(PHONE, FakeOtpProvider.CODE)).toBe(true); }); it("rejects a wrong code", async () => { await service.start(PHONE); expect(await service.check(PHONE, "000000")).toBe(false); }); it("does not allow a code to be used twice", async () => { await service.start(PHONE); await service.check(PHONE, FakeOtpProvider.CODE); await expect(service.check(PHONE, FakeOtpProvider.CODE)).rejects.toMatchObject({ code: "NO_PENDING_CODE" }); }); it("locks after 5 wrong attempts", async () => { await service.start(PHONE); for (let i = 0; i < 5; i++) await service.check(PHONE, "000000"); await expect(service.check(PHONE, FakeOtpProvider.CODE)).rejects.toMatchObject({ code: "TOO_MANY_ATTEMPTS" }); }); it("enforces a 60-second resend cooldown", async () => { await service.start(PHONE); await expect(service.start(PHONE)).rejects.toMatchObject({ code: "COOLDOWN" }); clock += 61_000; await expect(service.start(PHONE)).resolves.toBeUndefined(); }); it("expires codes after 5 minutes", async () => { await service.start(PHONE); clock += 5 * 60_000 + 1; await expect(service.check(PHONE, FakeOtpProvider.CODE)).rejects.toMatchObject({ code: "EXPIRED" }); }); it("rejects invalid phone numbers before calling the provider", async () => { await expect(service.start("12345")).rejects.toBeInstanceOf(OtpError); expect(provider.sent).toHaveLength(0); }); it("handles provider outages without burning the cooldown", async () => { provider.failNext = true; await expect(service.start(PHONE)).rejects.toMatchObject({ code: "PROVIDER_ERROR" }); await expect(service.start(PHONE)).resolves.toBeUndefined(); // retry works immediately }); }); 

These tests run in milliseconds, cost nothing, and cover cases that are painful to trigger by hand: expiry, lockout and a provider outage.

Step 5: test the SDK wrapper by mocking the SDK

You should also check that AuthlyProvider passes the right arguments. Mock the SDK module with Vitest's hoisted mocks:

import { describe, it, expect, vi, beforeEach } from "vitest"; const { sendMock, verifyMock } = vi.hoisted(() => ({ sendMock: vi.fn(), verifyMock: vi.fn(), })); vi.mock("authly-otp", () => ({ default: class { otp = { send: sendMock, verify: verifyMock }; }, })); import { AuthlyProvider } from "./authlyProvider"; describe("AuthlyProvider", () => { beforeEach(() => { sendMock.mockReset(); verifyMock.mockReset(); }); it("sends on WhatsApp with Telegram fallback", async () => { sendMock.mockResolvedValue({ otpId: "otp_1" }); const provider = new AuthlyProvider("test-key"); const result = await provider.send("+14155552671"); expect(result).toEqual({ otpId: "otp_1" }); expect(sendMock).toHaveBeenCalledWith({ to: "+14155552671", channel: "whatsapp", fallbackChannel: "telegram", lang: "en", }); }); it("returns false when the SDK throws on verify", async () => { verifyMock.mockRejectedValue(new Error("network")); const provider = new AuthlyProvider("test-key"); expect(await provider.verify("otp_1", "123456")).toBe(false); }); }); 

If you use Jest, the idea is the same: jest.mock("authly-otp", ...).

Step 6: end-to-end tests with Playwright

For browser tests, choose the provider from an environment variable. In your app's startup code (Express shown here):

import { AuthlyProvider } from "./otp/authlyProvider"; import { FakeOtpProvider } from "./otp/fakeProvider"; import { OtpService } from "./otp/service"; const useFake = process.env.OTP_PROVIDER === "fake"; if (useFake && process.env.NODE_ENV === "production") { throw new Error("The fake OTP provider must never run in production"Source:https://dev.to/authly/how-to-test-otp-login-in-nodejs-fakes-mocks-and-a-safe-smoke-test-vitest-or-jest-7gh

Related posts