Set OTPMOCK_URL=https://api.otpmock.com in your test environment, point the Bandwidth client at it, and use your otpmock API key as the Bandwidth credential. Your application code doesn't change, and production keeps sending real SMS through Bandwidth.
Setup
The SDK's basePath option is ignored for sending messages, because each operation has its own server URL. Override that URL from bandwidth-sdk/dist/base once at startup in the test environment.
import { Configuration, MessagesApi } from "bandwidth-sdk";
import { operationServerMap } from "bandwidth-sdk/dist/base";
if (process.env.OTPMOCK_URL) {
operationServerMap["MessagesApi.createMessage"][0].url = `${process.env.OTPMOCK_URL}/api/v2`;
}
export const bandwidth = new MessagesApi(
new Configuration({
username: process.env.BANDWIDTH_USERNAME,
password: process.env.BANDWIDTH_PASSWORD, // otpmock API key in tests
}),
);import os
from urllib.parse import urlparse
import bandwidth
class OtpMockApiClient(bandwidth.ApiClient):
"""Each Bandwidth operation has its own host; send them all to otpmock."""
def call_api(self, method, url, *args, **kwargs):
u = urlparse(url)
url = os.environ["OTPMOCK_URL"].rstrip("/") + u.path + ("?" + u.query if u.query else "")
return super().call_api(method, url, *args, **kwargs)
config = bandwidth.Configuration(
username=os.environ["BANDWIDTH_USERNAME"],
password=os.environ["BANDWIDTH_PASSWORD"], # otpmock API key in tests
)
client = OtpMockApiClient(config) if os.environ.get("OTPMOCK_URL") else bandwidth.ApiClient(config)
messages = bandwidth.MessagesApi(client)String base = System.getenv().getOrDefault("OTPMOCK_URL", "https://messaging.bandwidth.com");
String auth = Base64.getEncoder().encodeToString(
(System.getenv("BANDWIDTH_USERNAME") + ":" + System.getenv("BANDWIDTH_PASSWORD")).getBytes()); // password = otpmock API key in tests
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/api/v2/users/" + accountId + "/messages"))
.header("Authorization", "Basic " + auth)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json)) // {"applicationId":"...","to":["+1..."],"from":"+1...","text":"..."}
.build();// The Bandwidth .NET package has no host option, so call the Messaging API directly.
var baseUrl = Environment.GetEnvironmentVariable("OTPMOCK_URL") ?? "https://messaging.bandwidth.com";
var accountId = Environment.GetEnvironmentVariable("BANDWIDTH_ACCOUNT_ID");
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes(
$"{Environment.GetEnvironmentVariable("BANDWIDTH_USERNAME")}:{Environment.GetEnvironmentVariable("BANDWIDTH_PASSWORD")}")); // password = otpmock key in tests
using var http = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/api/v2/users/{accountId}/messages")
{
Content = JsonContent.Create(new { applicationId, to = new[] { phone }, from, text }),
};
req.Headers.Authorization = new AuthenticationHeaderValue("Basic", auth);
(await http.SendAsync(req)).EnsureSuccessStatusCode();use Bandwidth\Api\MessagesApi;
use Bandwidth\Configuration;
use GuzzleHttp\{Client, HandlerStack, Middleware};
use Psr\Http\Message\RequestInterface;
// createMessage has its own server URL, so tests swap the host on the Guzzle client.
$stack = HandlerStack::create();
if ($otpmock = getenv('OTPMOCK_URL')) {
$u = parse_url($otpmock);
$stack->push(Middleware::mapRequest(fn (RequestInterface $r) => $r->withUri(
$r->getUri()->withScheme($u['scheme'])->withHost($u['host'])->withPort($u['port'] ?? null))));
}
$config = (new Configuration())
->setUsername(getenv('BANDWIDTH_USERNAME'))
->setPassword(getenv('BANDWIDTH_PASSWORD')); // otpmock API key in tests
$bandwidth = new MessagesApi(new Client(['handler' => $stack]), $config);require "net/http"
require "json"
BANDWIDTH_URL = ENV.fetch("OTPMOCK_URL", "https://messaging.bandwidth.com")
uri = URI("#{BANDWIDTH_URL}/api/v2/users/#{ENV["BANDWIDTH_ACCOUNT_ID"]}/messages")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.basic_auth(ENV["BANDWIDTH_USERNAME"], ENV["BANDWIDTH_PASSWORD"]) # password = otpmock API key in tests
req.body = { applicationId: ENV["BANDWIDTH_APP_ID"], to: ["+15550142"], from: "+15550000001", text: "Your code is #{code}" }.to_json
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }// Bandwidth has no official Go SDK; call its HTTP API with net/http, only the host changes.
base := os.Getenv("OTPMOCK_URL")
if base == "" {
base = "https://messaging.bandwidth.com"
}
body, _ := json.Marshal(map[string]any{
"applicationId": os.Getenv("BANDWIDTH_APPLICATION_ID"), "to": []string{"+15550142"},
"from": os.Getenv("BANDWIDTH_NUMBER"), "text": msg,
})
req, _ := http.NewRequest("POST", base+"/api/v2/users/"+os.Getenv("BANDWIDTH_ACCOUNT_ID")+"/messages", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(os.Getenv("BANDWIDTH_USERNAME"), os.Getenv("BANDWIDTH_PASSWORD")) // password = otpmock key in tests
res, err := http.DefaultClient.Do(req) // 202 AcceptedEach 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, use your otpmock API key as the Bandwidth password (Basic auth). Don't configure OAuth client credentials in tests.
What otpmock emulates
| Endpoint | What it does |
|---|---|
POST /api/v2/users/{accountId}/messages | Send a message (applicationId, to[], from, text), 202 |
Responses and errors follow Bandwidth's own format, so the SDK parses them as usual. Authentication failures and an exhausted monthly allowance also come back in Bandwidth's error shape.
Phone numbers
Send in E.164 (+15550142).
How to tell your app uses Bandwidth
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:
bandwidth-sdkin package.jsonMessagesApicreateMessage(
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 Bandwidth
const { code } = await otp.waitForCode(phone, { since });The otp helper is a single file: get it from the docs. Full walkthroughs: Playwright, Cypress.
FAQ
Does otpmock send real SMS through Bandwidth?
No. In the test environment your app's Bandwidth requests go to otpmock, which stores the message for 10 minutes and never contacts Bandwidth or any carrier. Production keeps using Bandwidth because otpmock is only enabled when OTPMOCK_URL is set.
Is the official bandwidth-sdk SDK supported?
Yes. otpmock's Bandwidth endpoints are tested end to end with the official bandwidth-sdk package for Node.js. Other languages work too if their Bandwidth client lets you change the API host.
Which Bandwidth APIs does otpmock support?
POST /api/v2/users/{accountId}/messages (Send a message (applicationId, to[], from, text), 202).
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