Set OTPMOCK_URL=https://api.otpmock.com in your test environment, point the Vonage client at it, and use your otpmock API key as the Vonage credential. Your application code doesn't change, and production keeps sending real SMS through Vonage.
Setup
The SDK has documented restHost and apiHost options.
import { Vonage } from "@vonage/server-sdk";
export const vonage = new Vonage(
{
apiKey: process.env.VONAGE_API_KEY,
apiSecret: process.env.VONAGE_API_SECRET, // otpmock API key in tests
applicationId: process.env.VONAGE_APPLICATION_ID, // otpmock API key in tests (Verify v2)
privateKey: process.env.VONAGE_PRIVATE_KEY,
},
process.env.OTPMOCK_URL ? { restHost: process.env.OTPMOCK_URL, apiHost: process.env.OTPMOCK_URL } : {},
);import os
from urllib.parse import urlparse
from vonage import Auth, HttpClientOptions, Vonage
otpmock = os.environ.get("OTPMOCK_URL") # e.g. https://api.otpmock.com
host = urlparse(otpmock).netloc if otpmock else None
vonage = Vonage(
Auth(api_key=os.environ["VONAGE_API_KEY"], api_secret=os.environ["VONAGE_API_SECRET"]), # secret = otpmock key in tests
HttpClientOptions(api_host=host, rest_host=host) if host else None,
)
# Verify v2 uses an application JWT (otpmock reads application_id, ignores the signature)
verify = Vonage(
Auth(application_id=os.environ["VONAGE_APPLICATION_ID"], # otpmock API key in tests
private_key=os.environ["VONAGE_PRIVATE_KEY"]),
HttpClientOptions(api_host=host) if host else None,
).verifyimport com.vonage.client.HttpConfig;
import com.vonage.client.VonageClient;
String otpmock = System.getenv("OTPMOCK_URL");
VonageClient.Builder builder = VonageClient.builder()
.apiKey(System.getenv("VONAGE_API_KEY"))
.apiSecret(System.getenv("VONAGE_API_SECRET")); // otpmock API key in tests
if (otpmock != null) builder.httpConfig(HttpConfig.builder().baseUri(otpmock).build());
VonageClient vonage = builder.build();// The Vonage .NET SDK reads its hosts from configuration (appsettings.json).
// In the test environment:
{
"vonage": {
"Url.Rest": "https://api.otpmock.com",
"Url.Api": "https://api.otpmock.com"
}
}
// Code stays the same:
var vonage = new VonageClient(Credentials.FromApiKeyAndSecret(apiKey, apiSecret)); // secret = otpmock key in tests
// Verify v2 over HTTPS (Basic auth with key and secret):
var vonageUrl = Environment.GetEnvironmentVariable("OTPMOCK_URL") ?? "https://api.nexmo.com";
var http = new HttpClient { BaseAddress = new Uri(vonageUrl) };
http.DefaultRequestHeaders.Authorization = new("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{apiKey}:{apiSecret}")));
// POST /v2/verify { brand, workflow = [{ channel = "sms", to }] } -> request_id
// POST /v2/verify/{request_id} { code } -> { status = "completed" }use Vonage\Client;
use Vonage\Client\Credentials\Basic;
$otpmock = getenv('OTPMOCK_URL');
$vonage = new Client(
new Basic(getenv('VONAGE_API_KEY'), getenv('VONAGE_API_SECRET')), // secret = otpmock key in tests
$otpmock ? ['base_rest_url' => $otpmock, 'base_api_url' => $otpmock] : [],
);
// Verify v2: application JWT (application_id = otpmock key in tests; signature not checked).
// verify2() hard-codes api.nexmo.com, so tests pass a host-rewriting Guzzle client.
$stack = \GuzzleHttp\HandlerStack::create();
if ($otpmock) {
$u = parse_url($otpmock);
$stack->push(\GuzzleHttp\Middleware::mapRequest(fn ($r) => $r->withUri(
$r->getUri()->withScheme($u['scheme'])->withHost($u['host'])->withPort($u['port'] ?? null))));
}
$verify = new Client(
new \Vonage\Client\Credentials\Keypair(file_get_contents(getenv('VONAGE_PRIVATE_KEY_PATH')), getenv('VONAGE_APPLICATION_ID')),
[], new \GuzzleHttp\Client(['handler' => $stack]),
);require "vonage"
require "uri"
otpmock = ENV["OTPMOCK_URL"] && URI(ENV["OTPMOCK_URL"])
host = otpmock && "#{otpmock.host}:#{otpmock.port}"
vonage = Vonage::Client.new(
api_key: ENV["VONAGE_API_KEY"],
api_secret: ENV["VONAGE_API_SECRET"], # otpmock API key in tests
**(host ? { api_host: host, rest_host: host } : {})
)
# Verify v2 (JWT): otpmock reads application_id as the key; signature not checked
verify = Vonage::Client.new(
application_id: ENV["VONAGE_APPLICATION_ID"], # otpmock API key in tests
private_key: File.read(ENV["VONAGE_PRIVATE_KEY_PATH"]),
**(host ? { api_host: host } : {})
).verify2auth := vonage.CreateAuthFromKeySecret(os.Getenv("VONAGE_API_KEY"), os.Getenv("VONAGE_API_SECRET")) // secret = otpmock key in tests
smsClient := vonage.NewSMSClient(auth)
if base := os.Getenv("OTPMOCK_URL"); base != "" {
smsClient.Config.BasePath = base + "/sms"
}
// Verify v2 (net/http): POST {base}/v2/verify, then POST {base}/v2/verify/{request_id} {"code": ...}
verifyBase := "https://api.nexmo.com"
if base := os.Getenv("OTPMOCK_URL"); base != "" {
verifyBase = base
}
req, _ := http.NewRequest("POST", verifyBase+"/v2/verify", bytes.NewReader(body))
req.SetBasicAuth(os.Getenv("VONAGE_API_KEY"), os.Getenv("VONAGE_API_SECRET")) // secret = otpmock key in testsEach 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 VONAGE_API_SECRET to your otpmock API key (SMS and Messages APIs use Basic auth). For Verify v2, which the SDK signs with a JWT, also set VONAGE_APPLICATION_ID to your otpmock API key; otpmock reads the JWT's application_id claim and does not check the signature, so your usual private key works.
What otpmock emulates
| Endpoint | What it does |
|---|---|
POST /sms/json | SMS API (rest.nexmo.com): send an SMS |
POST /v1/messages | Messages API with channel sms and message_type text |
POST /v2/verify | Verify v2: start a verification (otpmock generates the code; code_length and code are honoured) |
POST /v2/verify/{request_id} | Verify v2: check a code (200 completed, 400 wrong, 410 after 3 wrong attempts) |
DELETE /v2/verify/{request_id} | Verify v2: cancel |
Responses and errors follow Vonage's own format, so the SDK parses them as usual. Authentication failures and an exhausted monthly allowance also come back in Vonage's error shape.
Phone numbers
Vonage sends numbers without a leading + (15550142). otpmock stores them as +15550142, so tests can query the E.164 form.
How to tell your app uses Vonage
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:
@vonage/server-sdkornexmoin package.jsonvonage.sms.send(vonage.messages.send(vonage.verify2.newRequest(
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 Vonage
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
- Like Vonage, otpmock rejects a second concurrent Verify request to the same number with 409 until the first completes, is cancelled or expires.
FAQ
Does otpmock send real SMS through Vonage?
No. In the test environment your app's Vonage requests go to otpmock, which stores the message for 10 minutes and never contacts Vonage or any carrier. Production keeps using Vonage because otpmock is only enabled when OTPMOCK_URL is set.
Is the official @vonage/server-sdk SDK supported?
Yes. otpmock's Vonage endpoints are tested end to end with the official @vonage/server-sdk package for Node.js. Other languages work too if their Vonage client lets you change the API host.
Which Vonage APIs does otpmock support?
POST /sms/json (SMS API (rest.nexmo.com): send an SMS); POST /v1/messages (Messages API with channel sms and message_type text); POST /v2/verify (Verify v2: start a verification (otpmock generates the code; code_length and code are honoured)); POST /v2/verify/{request_id} (Verify v2: check a code (200 completed, 400 wrong, 410 after 3 wrong attempts)); DELETE /v2/verify/{request_id} (Verify v2: cancel).
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