Assert that an email was sent exactly once, or not at all
Most email tests prove that a message arrived. Some of the most valuable ones prove the opposite: that an address which does not exist gets no password-reset email, that a user who opted out gets no notification, or that one click on "Sign up" produced one email and not two. These tests are harder, because "nothing happened" can be true for two reasons: the app behaved correctly, or the email is only late. This guide shows how to write them with AssertInbox, how to choose the waiting time, and what a pass actually means.
Absence is evidence, not proof
GET /v1/wait long-polls for up to 25 seconds and answers 408 timeout when nothing matching has arrived. A negative test turns that into a pass. But a 408 only says that no email arrived in that window. If your mail provider sometimes needs 30 seconds, a test with a 10 second window would pass while the bug is still there. Two habits make these tests useful anyway:
- Prove the pipeline works in the same test. Send a second, positive email to a control address right after the one that should not exist, and wait for the control first. When the control arrives, the mail path was alive in that period, so a missing email is meaningful.
- Choose the quiet period from your own data. Measure how long your positive tests wait for the email, take the slowest runs, and use a window clearly longer than that. Write the number down in the test, with the reason.
Get an API key
Get one in a click at /start. One request creates a key and your private namespace, with no email address or card. The key is shown once, so keep it in your secret store and export ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). Use inboxes only for services you own or control; see the terms. Limits and error codes are on the limits page, and the client files can replace the helper functions below.
The test file
Save this as no-email.test.js and run it with node --test on Node 18 or newer. The app routes (/api/password-reset, /api/signup, /api/preferences) are placeholders for your own staging API; use only an app you own. The three helpers are the interesting part: expectNoEmail for negative checks, messagesFor for counting, and waitForEmail with a 408 retry loop for slow background jobs.
const { test, after } = require("node:test");
const assert = require("node:assert");
const API = "https://assertinbox.com";
const KEY = process.env.ASSERTINBOX_KEY;
const NAMESPACE = process.env.ASSERTINBOX_NAMESPACE;
const APP = process.env.APP_URL || "http://localhost:3000";
const QUIET_SECONDS = Number(process.env.QUIET_SECONDS || 10);
const GRACE_MS = Number(process.env.GRACE_MS || 8000);
const tags = [];
const auth = { Authorization: "Bearer " + KEY };
function newInbox(prefix) {
const tag = (prefix + "-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8)).toLowerCase();
tags.push(tag);
return { tag, email: NAMESPACE + "." + tag + "@assertinbox.com" };
}
async function waitOnce(tag, seconds, filters = {}) {
const params = new URLSearchParams({ tag, timeout: String(seconds), ...filters });
const res = await fetch(API + "/v1/wait?" + params, { headers: auth });
if (res.status === 200) return res.json();
if (res.status === 408) return null;
throw new Error("AssertInbox returned HTTP " + res.status);
}
async function waitForEmail(tag, filters = {}, attempts = 3) {
for (let i = 0; i < attempts; i++) {
const mail = await waitOnce(tag, 25, filters);
if (mail) return mail;
}
throw new Error("No email arrived for tag " + tag);
}
async function expectNoEmail(tag, filters = {}) {
const mail = await waitOnce(tag, QUIET_SECONDS, filters);
assert.strictEqual(mail, null, "unexpected email: " + (mail && mail.subject));
}
async function messagesFor(tag) {
const res = await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { headers: auth });
assert.strictEqual(res.status, 200);
return (await res.json()).messages;
}
async function post(path, body) {
const res = await fetch(APP + path, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
assert.ok(res.status < 500, path + " returned " + res.status);
return res;
}
after(async () => {
for (const tag of tags) {
await fetch(API + "/v1/messages?tag=" + encodeURIComponent(tag), { method: "DELETE", headers: auth });
}
});
test("a reset request for an unknown account sends no email", { timeout: 120000 }, async () => {
const unknown = newInbox("reset-unknown");
const control = newInbox("reset-control");
await post("/api/password-reset", { email: unknown.email });
await post("/api/signup", { email: control.email });
await waitForEmail(control.tag);
await expectNoEmail(unknown.tag);
});
test("a user who opted out gets no notification", { timeout: 120000 }, async () => {
const user = newInbox("optout");
const control = newInbox("optout-control");
for (const inbox of [user, control]) await post("/api/signup", { email: inbox.email });
await waitForEmail(user.tag, { subject: "verify" });
await waitForEmail(control.tag, { subject: "verify" });
await post("/api/preferences", { email: user.email, notifications: false });
await post("/api/test/send-notification", { email: user.email });
await post("/api/test/send-notification", { email: control.email });
await waitForEmail(control.tag, { subject: "notification" });
await expectNoEmail(user.tag, { subject: "notification" });
});
test("sign-up sends exactly one verification email", { timeout: 120000 }, async () => {
const inbox = newInbox("once");
await post("/api/signup", { email: inbox.email });
const first = await waitForEmail(inbox.tag);
await new Promise((resolve) => setTimeout(resolve, GRACE_MS));
const all = await messagesFor(inbox.tag);
assert.strictEqual(all.length, 1, "expected one email, got " + all.map((m) => m.subject).join(" | "));
assert.strictEqual(all[0].id, first.id);
});
Run it with the key in the environment:
export ASSERTINBOX_KEY=ai_your_key_here
export ASSERTINBOX_NAMESPACE=your_namespace
APP_URL=https://staging.example.com QUIET_SECONDS=15 node --test no-email.test.js
The control tag in the first two tests is what gives the negative check its value. The control email is requested after the one that must not exist, so once it has arrived the mail provider has had at least that long to deliver the other one.
Counting emails: duplicates
A duplicate is a different failure from a missing email, and wait cannot see it: it returns the newest matching message and stays silent about the others. The third test therefore waits for the first message, pauses for a grace period, and then lists everything for the tag with GET /v1/messages?tag=. Duplicates usually come from retried jobs or from a form that submits twice, so the grace period should be longer than your job queue's retry delay. If your queue retries after a minute, an 8 second grace period will not find the bug; set GRACE_MS to match.
Slow background jobs
Digest emails and delayed reminders run on a schedule and can take minutes. Do not raise one wait to a huge value. The service answers at most 25 seconds per call, so loop: call wait again after every 408, with a fixed number of attempts. waitForEmail above takes an attempts argument for that. A test that waits for ten minutes is usually better run as a scheduled check than in every pull request.
Choosing the quiet period
- Run the positive version of the test (the email should arrive) twenty times and note the longest delay.
- Set the quiet period to at least twice that, but not more than you can afford in CI: every negative test spends the full period.
- Run the negative tests in parallel with other tests. They use unique tags, so they do not interfere, and the waiting overlaps.
- Revisit the number when you change email providers or add a queue.
Pass the since or after filters when the same tag could hold older mail. Tags in this guide are unique per run, so they are not needed here.
Troubleshooting
- The negative test passes even though you know an email is sent. The quiet period is shorter than the delivery time, or a
subjectfilter does not match. Run the positive version first. - The control never arrives. The mail path is down or misconfigured; fix that before reading anything into the negative result.
- The duplicate test fails sometimes. Look at the subjects it prints. Two different emails (a welcome and a verification) are not a duplicate; add a
subjectfilter to the count. - HTTP 429. The key used its 2,000 requests for the day; see the limits page.
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.