Set OTPMOCK_URL=https://api.otpmock.com in your test environment, point the Twilio client at it, and use your otpmock API key as the Twilio credential. Your application code doesn't change, and production keeps sending real SMS through Twilio.
Setup
The official SDK accepts a custom HTTP client. This one keeps every path and swaps the host, so both api.twilio.com and verify.twilio.com traffic reaches otpmock. Download it from https://otpmock.com/sdk/twilio-node-client.mjs.
import twilio from "twilio";
import { OtpMockHttpClient } from "./twilio-node-client.mjs";
export const sms = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN, {
httpClient: process.env.OTPMOCK_URL ? new OtpMockHttpClient(process.env.OTPMOCK_URL) : undefined,
});import os
from urllib.parse import urlparse
from twilio.http.http_client import TwilioHttpClient
from twilio.rest import Client
class OtpMockHttpClient(TwilioHttpClient):
"""Sends Twilio SDK requests to otpmock, keeping path, params and auth."""
def __init__(self, base):
super().__init__()
self.base = base.rstrip("/")
def request(self, method, url, *args, **kwargs):
u = urlparse(url)
return super().request(method, self.base + u.path + ("?" + u.query if u.query else ""), *args, **kwargs)
otpmock = os.environ.get("OTPMOCK_URL")
client = Client(
os.environ["TWILIO_ACCOUNT_SID"],
os.environ["TWILIO_AUTH_TOKEN"], # otpmock API key in tests
http_client=OtpMockHttpClient(otpmock) if otpmock else None,
)import com.twilio.http.*;
import java.net.URI;
// Sends Twilio SDK requests to otpmock, keeping path, params and auth.
public class OtpMockTwilioHttpClient extends NetworkHttpClient {
private final String base;
public OtpMockTwilioHttpClient(String base) { this.base = base.replaceAll("/+$", ""); }
@Override
public Response makeRequest(Request request) {
Request routed = new Request(request.getMethod(), base + URI.create(request.getUrl()).getRawPath());
request.getQueryParams().forEach((k, vs) -> vs.forEach(v -> routed.addQueryParam(k, v)));
request.getPostParams().forEach((k, vs) -> vs.forEach(v -> routed.addPostParam(k, v)));
request.getHeaderParams().forEach((k, vs) -> vs.forEach(v -> routed.addHeaderParam(k, v)));
routed.setAuth(request.getUsername(), request.getPassword());
return super.makeRequest(routed);
}
}
// Where you build the client:
String otpmock = System.getenv("OTPMOCK_URL");
TwilioRestClient.Builder builder = new TwilioRestClient.Builder(accountSid, authToken); // otpmock API key in tests
if (otpmock != null) builder.httpClient(new OtpMockTwilioHttpClient(otpmock));
TwilioRestClient client = builder.build();
// Message.creator(...).create(client);using Twilio.Clients;
using Twilio.Http;
// Sends requests to otpmock, keeping path, query and auth headers.
class OtpMockHandler : DelegatingHandler
{
private readonly Uri _base;
public OtpMockHandler(string baseUrl) : base(new HttpClientHandler()) => _base = new Uri(baseUrl);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
request.RequestUri = new Uri(_base, request.RequestUri!.PathAndQuery);
return base.SendAsync(request, ct);
}
}
var otpmock = Environment.GetEnvironmentVariable("OTPMOCK_URL");
var client = new TwilioRestClient(
accountSid,
authToken, // otpmock API key in tests
httpClient: otpmock is null ? null : new SystemNetHttpClient(new HttpClient(new OtpMockHandler(otpmock))));
// await MessageResource.CreateAsync(..., client: client);use Twilio\Http\CurlClient;
use Twilio\Rest\Client;
// Sends Twilio SDK requests to otpmock, keeping path, params and auth.
class OtpMockTwilioClient extends CurlClient {
public function __construct(private string $base) { parent::__construct(); }
public function request(string $method, string $url, array $params = [], array $data = [], array $headers = [],
?string $user = null, ?string $password = null, ?int $timeout = null, ?\Twilio\AuthStrategy\AuthStrategy $authStrategy = null): \Twilio\Http\Response {
return parent::request($method, rtrim($this->base, '/') . parse_url($url, PHP_URL_PATH), $params, $data, $headers, $user, $password, $timeout, $authStrategy);
}
}
$otpmock = getenv('OTPMOCK_URL');
$client = new Client(
getenv('TWILIO_ACCOUNT_SID'),
getenv('TWILIO_AUTH_TOKEN'), // otpmock API key in tests
null, null,
$otpmock ? new OtpMockTwilioClient($otpmock) : null,
);require "twilio-ruby"
require "uri"
# Sends Twilio SDK requests to otpmock, keeping path, params and auth.
class OtpMockHttpClient < Twilio::HTTP::Client
def initialize(base)
super()
@base = URI(base)
end
def request(_host, _port, method, url, *rest)
u = URI(url)
path = u.path + (u.query ? "?#{u.query}" : "")
super("#{@base.scheme}://#{@base.host}", @base.port, method, "#{@base.scheme}://#{@base.host}:#{@base.port}#{path}", *rest)
end
end
otpmock = ENV["OTPMOCK_URL"]
client = Twilio::REST::Client.new(
ENV["TWILIO_ACCOUNT_SID"],
ENV["TWILIO_AUTH_TOKEN"], # otpmock API key in tests
nil, nil,
otpmock ? OtpMockHttpClient.new(otpmock) : nil
)// otpmockTransport sends SDK requests to otpmock, keeping path, query and auth.
type otpmockTransport struct{ base *url.URL }
func (t otpmockTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.URL.Scheme, r.URL.Host, r.Host = t.base.Scheme, t.base.Host, t.base.Host
return http.DefaultTransport.RoundTrip(r)
}
func newTwilio() *twilio.RestClient {
// token = otpmock API key in tests. twilio-go only accepts letters and digits here,
// so use the key without underscores (om_live_abc… -> omliveabc…); otpmock accepts both forms.
sid, token := os.Getenv("TWILIO_ACCOUNT_SID"), os.Getenv("TWILIO_AUTH_TOKEN")
params := twilio.ClientParams{Username: sid, Password: token}
if base, err := url.Parse(os.Getenv("OTPMOCK_URL")); err == nil && base.Host != "" {
c := &client.Client{Credentials: client.NewCredentials(sid, token), HTTPClient: &http.Client{Transport: otpmockTransport{base}}}
c.SetAccountSid(sid)
params.Client = c
}
return twilio.NewRestClientWithParams(params)
}Each language is tested in CI against otpmock with the provider's official SDK, or its plain HTTP API where no SDK can be pointed at another host.
Credentials. In the test environment, set TWILIO_AUTH_TOKEN to your otpmock API key. The Account SID can stay as it is; otpmock echoes it back.
What otpmock emulates
| Endpoint | What it does |
|---|---|
POST /2010-04-01/Accounts/{AccountSid}/Messages.json | Programmable Messaging: send an SMS |
POST /v2/Services/{ServiceSid}/Verifications | Verify v2: start a verification (otpmock generates a 6-digit code) |
POST /v2/Services/{ServiceSid}/VerificationCheck | Verify v2: check a code (approved / pending, 5 attempts) |
Responses and errors follow Twilio's own format, so the SDK parses them as usual. Authentication failures and an exhausted monthly allowance also come back in Twilio's error shape.
Phone numbers
Send in E.164 (+15550142), as Twilio expects.
How to tell your app uses Twilio
Look for any of these in your codebase to confirm where the SMS is sent, and therefore where the otpmock option has to be set:
twilioin package.jsonclient.messages.create(verify.v2.services(...)
Read the code in your tests
const phone = otp.randomPhone();
const since = Date.now() - 5_000;
await page.getByRole("button", { name: "Send code" }).click(); // your app calls Twilio
const { code } = await otp.waitForCode(phone, { since });The otp helper is a single file: get it from the docs. Full walkthroughs: Playwright, Cypress.
Good to know
- Twilio's own test credentials only cover a few resources and not Verify; otpmock covers both Messaging and Verify.
- The Go SDK (twilio-go) rejects auth tokens containing anything but letters and digits. Use your otpmock key without underscores (
om_live_abc…becomesomliveabc…); otpmock treats both forms as the same key.
FAQ
Does otpmock send real SMS through Twilio?
No. In the test environment your app's Twilio requests go to otpmock, which stores the message for 10 minutes and never contacts Twilio or any carrier. Production keeps using Twilio because otpmock is only enabled when OTPMOCK_URL is set.
Is the official twilio SDK supported?
Yes. otpmock's Twilio endpoints are tested end to end with the official twilio package for Node.js. Other languages work too if their Twilio client lets you change the API host.
Which Twilio APIs does otpmock support?
POST /2010-04-01/Accounts/{AccountSid}/Messages.json (Programmable Messaging: send an SMS); POST /v2/Services/{ServiceSid}/Verifications (Verify v2: start a verification (otpmock generates a 6-digit code)); POST /v2/Services/{ServiceSid}/VerificationCheck (Verify v2: check a code (approved / pending, 5 attempts)).
The free plan includes 300 messages a month. Using an AI coding assistant? Point it at otpmock.com/llms-full.txt.
Get a free API key