Appium email OTP test for mobile apps
Mobile apps that verify an email address send a one-time code, and an Appium test has to read it from a real inbox. This guide uses WebdriverIO with Appium 2, in plain JavaScript and Mocha. The test types a unique address into the app, waits for the email through one HTTP call from the Node process, and types the code into the next screen. The email wait never touches the device, so the same test runs on an emulator, a simulator or a device farm.
How it works
Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, with otp, magic_link and links already extracted. Messages are deleted after 24 hours.
Get an API key
Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export both values for the tests: ASSERTINBOX_KEY is the api_key and ASSERTINBOX_NAMESPACE is the namespace. If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.
Set up WebdriverIO with Appium 2
Install the runner, the Appium service and a driver. Appium 2 keeps drivers separate from the server, so install the one for your platform: uiautomator2 for Android or xcuitest for iOS.
npm install --save-dev @wdio/cli @wdio/local-runner @wdio/mocha-framework @wdio/spec-reporter @wdio/appium-service appium
npx appium driver install uiautomator2
Save this as wdio.conf.js. The capabilities are deliberately generic: the app path, the platform and the driver come from environment variables, and you add whatever your device or farm needs, such as a device name or a platform version.
exports.config = {
runner: "local",
port: 4723,
specs: ["./test/specs/**/*.js"],
maxInstances: 1,
capabilities: [
{
platformName: process.env.PLATFORM_NAME || "Android",
"appium:automationName": process.env.AUTOMATION_NAME || "UiAutomator2",
"appium:app": process.env.APP_PATH,
"appium:newCommandTimeout": 240,
},
],
services: [["appium", { command: "appium" }]],
framework: "mocha",
reporters: ["spec"],
mochaOpts: { ui: "bdd", timeout: 180000 },
};
The inbox helper
Put this in test/support/inbox.js. It needs Node 18 or newer for the built-in fetch. Because the helper runs in the Node process that drives Appium, the key never reaches the device or the app under test.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
function newInbox(prefix) {
const random = Math.random().toString(36).slice(2, 8);
const tag = (prefix + "-" + Date.now() + "-" + random).toLowerCase();
return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}
async function waitForEmail(tag, filters = {}) {
const params = new URLSearchParams({ tag, timeout: "25", ...filters });
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(API + "/v1/wait?" + params, {
headers: { Authorization: "Bearer " + KEY },
});
if (res.status === 200) return res.json();
if (res.status !== 408) throw new Error("AssertInbox returned HTTP " + res.status);
}
throw new Error("No email arrived for tag " + tag);
}
async function deleteEmails(tag) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), {
method: "DELETE",
headers: { Authorization: "Bearer " + KEY },
});
}
module.exports = { newInbox, waitForEmail, deleteEmails };
The test
Save this as test/specs/signup.js. The selectors are accessibility ids, written ~name in WebdriverIO. They map to content-desc on Android and to the accessibility identifier on iOS. They depend on your app: replace email-input, signup-button and the others with the ids your developers set, and ask them to add the ids if they are missing. Each test builds its own address, so tests never read each other's mail.
const assert = require("node:assert");
const { newInbox, waitForEmail, deleteEmails } = require("../support/inbox");
describe("mobile sign-up email OTP", () => {
let inbox;
beforeEach(async () => {
inbox = newInbox("appium");
});
afterEach(async () => {
await deleteEmails(inbox.tag);
});
it("verifies the account with the code from the email", async () => {
await $("~email-input").setValue(inbox.email);
await $("~signup-button").click();
const mail = await waitForEmail(inbox.tag);
assert.match(mail.otp || "", /^[0-9]{4,8}$/, "subject was " + mail.subject);
const codeField = await $("~code-input");
await codeField.waitForDisplayed({ timeout: 15000 });
await codeField.setValue(mail.otp);
await $("~verify-button").click();
await $("~welcome-title").waitForDisplayed({ timeout: 15000 });
assert.strictEqual(await $("~welcome-title").getText(), "Email verified");
});
it("sends a new code when the user taps resend", async () => {
await $("~email-input").setValue(inbox.email);
await $("~signup-button").click();
const first = await waitForEmail(inbox.tag);
await $("~resend-button").click();
const second = await waitForEmail(inbox.tag, { after: first.id });
assert.notStrictEqual(second.id, first.id);
assert.match(second.otp || "", /^[0-9]{4,8}$/);
});
});
Start the run with npx wdio run wdio.conf.js, with APP_PATH pointing at your .apk or .app build and a booted emulator or simulator.
Waiting for the screen and for the email
The email wait is one request that the server holds open until a matching message arrives, so it returns as soon as the email does. Do the waits in this order: submit the form in the app, wait for the email, then wait for the code field with waitForDisplayed. The Mocha timeout has to be longer than all waits together; the config above uses 180 seconds.
Using a magic link on a device
If the app sends a link instead of a code, mail.magic_link holds it. An app that opens HTTPS links through app links or universal links needs the device to resolve them, and a staging build often uses its own scheme. Check what your build registers before choosing a method. On Android you can open the link with driver.execute("mobile: deepLink", { url: mail.magic_link, package: "com.example.app" }), replacing the package with yours. On iOS, opening a link normally goes through Safari first, so test the code flow if you can.
Troubleshooting
- Element not found. The accessibility id in the test does not match the app. Inspect the screen with Appium Inspector and use the id it shows.
- The wait times out. The app did not send the email or sent it to another address. Log
inbox.emailand compare it with your backend logs. Staging backends often block outgoing mail to unknown domains. - HTTP 401. The key is missing or wrong in the environment that starts WebdriverIO.
- HTTP 429. The key used its 2,000 requests for the day.
Retry-Aftergives the seconds until 00:00 UTC. - Session ends while waiting. Raise
appium:newCommandTimeout, which closes idle sessions, above the longest email wait. - The keyboard hides the button. Hide the keyboard with
driver.hideKeyboard()before tapping, where the platform supports it.
Next steps
For unique tags, the trigger-then-wait order, retries and cleanup in one place, read Reliable email tests. More stacks are on the guides page.