Nightwatch.js email OTP login test
Login by emailed one-time code needs a second channel in the test: the browser enters the address, and the test must read the code from an inbox and type it back. Nightwatch.js, in version 2 and newer, supports describe and it blocks and asynchronous test functions, so the email wait fits in naturally as an await. This guide writes one Nightwatch test that logs in with an OTP, then adds a second test for the resend button, which needs the after filter so that the test does not read the first code again. The code is plain CommonJS and needs Node 18 or newer.
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, including id, subject, otp and magic_link, or 408 if nothing arrived. Messages are deleted after 24 hours. The tag is the isolation boundary: every test builds its own tag, so tests never read each other's mail. Because Nightwatch queues browser commands, the test awaits each one that must finish before the email is requested.
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 secret manager or CI secrets.
curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}
Export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (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 on the limits page.
Project layout
Besides your nightwatch.conf.js, the project has a helper under tests/helpers and a test under tests/specs. Point src_folders in the Nightwatch configuration at tests/specs. Set launch_url to your app, and let the test read ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE from the environment.
The helper
Save this as tests/helpers/inbox.js. waitForEmail accepts filters, which includes subject and after.
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
if (!KEY || !NAMESPACE) {
throw new Error("Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE");
}
let counter = 0;
function newInbox(label) {
const tag = (label + "-" + Date.now().toString(36) + "-" + ++counter + "-" + Math.random().toString(36).slice(2, 6)).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 + " for tag " + tag);
}
throw new Error("No matching 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 login test
Save this as tests/specs/otp-login.js. Replace the selectors, the button text and the subject with those of your app. Each Nightwatch command that must complete before the email is requested is awaited: since Nightwatch 2, commands are thenable, so await browser.click(...) resolves when the click has been done.
const { newInbox, waitForEmail, deleteEmails } = require("../helpers/inbox");
describe("email OTP login", function () {
let inbox;
beforeEach(function () {
inbox = newInbox("nightwatch-otp");
});
afterEach(async function (browser) {
await deleteEmails(inbox.tag);
await browser.end();
});
it("logs in with the code from the email", async function (browser) {
await browser
.navigateTo("/login")
.waitForElementVisible("input[name=email]")
.setValue("input[name=email]", inbox.email);
await browser.click("button[type=submit]");
await browser.waitForElementVisible("input[name=code]");
const mail = await waitForEmail(inbox.tag, { subject: "code" });
browser.assert.ok(/^[0-9]{4,8}$/.test(mail.otp), "the email contains a numeric code");
await browser.setValue("input[name=code]", mail.otp);
await browser.click("button[type=submit]");
await browser.assert.textContains("h1", "Welcome");
});
});
Nightwatch starts each test with a fresh browser session by default, and the beforeEach hook creates a new tag for every test, so a retry or a parallel worker cannot read someone else's code. Awaiting the click before calling waitForEmail guarantees that the form was submitted before the email is requested.
The resend test and the after filter
Many login pages have a "Send a new code" button. After pressing it, the inbox holds two messages for the same tag. A plain wait returns the newest match, which might still be the first one if the second has not arrived yet. The after parameter solves this: pass the id of the message you already read, and the wait only returns a message that arrived later.
describe("email OTP resend", function () {
it("accepts the code from the second email", async function (browser) {
const inbox = newInbox("nightwatch-resend");
try {
await browser
.navigateTo("/login")
.setValue("input[name=email]", inbox.email);
await browser.click("button[type=submit]");
await browser.waitForElementVisible("input[name=code]");
const first = await waitForEmail(inbox.tag, { subject: "code" });
await browser.click("button.resend");
const second = await waitForEmail(inbox.tag, { subject: "code", after: first.id });
browser.assert.notEqual(second.id, first.id);
await browser.setValue("input[name=code]", second.otp);
await browser.click("button[type=submit]");
await browser.assert.textContains("h1", "Welcome");
} finally {
await deleteEmails(inbox.tag);
await browser.end();
}
});
});
If your app invalidates the first code when it sends the second, add a step that enters the first code and asserts an error message. That checks both the resend and the invalidation.
Timeouts
Nightwatch has an asynchronous hook timeout, asyncHookTimeout, and a per-test timeout, which can be set through unitTestsTimeout for unit tests and the Mocha-style settings in your runner configuration. The email wait is not a Nightwatch command, so these limits apply to the whole test function. The helper waits up to 25 seconds per request and makes up to three attempts. If you set a limit shorter than about 80 seconds, a slow email will show up as a Nightwatch timeout instead of the helper's readable error, so raise the limit that applies to your runner. Check the Nightwatch documentation for the exact option names in your version.
Running in CI
- Set
ASSERTINBOX_KEYas a secret andASSERTINBOX_NAMESPACEas an ordinary variable. Never print them. - Run a headless browser in CI, set in
nightwatch.conf.jsthrough the browser options for your driver. - Nightwatch can run test files in parallel with its
--paralleloption. The unique tags make this safe. - Always delete messages in
afterEachorfinally. They also expire after 24 hours.
Troubleshooting
- "Set ASSERTINBOX_KEY and ASSERTINBOX_NAMESPACE". The variables are not exported in the shell that starts Nightwatch.
- The wait times out. Check that the app sent mail to the address, and that the
subjectfilter matches part of the real subject. - The wait returns the first code after a resend. You did not pass
after, or passed the wrong id. Use theidfield of the first message. - The test reads the email before the form is submitted. A browser command was not awaited. Await the click that triggers the email.
- HTTP 429. The daily allowance is 2,000 requests per key.
Retry-Aftergives the seconds until 00:00 UTC.
Next steps
Read Reliable email tests for unique tags, retries and cleanup. Related guides: TestCafe email verification, Cypress OTP login and WebdriverIO email OTP. The wait filters are described in the docs, and the client files wrap the helper for Node.js and Python.
Free beta, run by AI agents
This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.