測試中不要再用 /\d{6}/ 提取驗證碼
Stop using /\d{6}/ to read verification codes in your tests
文章説明,測試以 `/\d{6}/` 從驗證電郵提取驗證碼,容易誤選訂單號碼、年份、價格或連結中的數字,並提出按上下文關鍵詞篩選的方法。做法包括使用電郵文字而非 HTML、先移除連結,篩選 4 至 8 位數或帶連字號、空格的數字,排除年份及訂單等號碼,再選取最接近「code」等關鍵詞的候選值。
Every sign-up test with a verification code reaches the same point: the email arrived, and now you need to get 482913 out of it. The first try is usually this:
const code = email.text.match(/\d{6}/)?.[0];
It works on the first email and breaks on the tenth. This post shows why, how to write a more reliable version, and how saci.cc hands you the code already extracted so you don't need either.
Why /\d{6}/ breaks
A real email has plenty of numbers besides the code:
- Order and ticket numbers: "Order #120394 · Your code is 482913". The regex picks the order, which comes first.
-
Prices, dates and times: "$149.90", "11/22/2026", "valid until 14:30". With
\d{4,8}, the year 2026 becomes a code. -
Links: the HTML has URLs like
/confirm?token=839201&uid=1002931. Run on the HTML, the regex finds numbers inside links. -
CSS and colors:
#120394in astylehas six digits. - Other formats: "482-913", "482 913" or "K7P2QX". A six-digits-in-a-row regex misses all of them.
- Phone numbers and zip codes in the footer.
And when it's wrong, it's wrong quietly: the test types the wrong number, the app refuses it, and the failure looks like a sign-up bug.
Look for the word, not just the number
What sets the code apart from the other numbers is the text around it: "code", "verification", "password", "OTP". A more reliable approach:
- Use the email's text, not the HTML, and blank out links before searching.
- Find candidates: 4 to 8 digits, or
123-456and123 456, not stuck to other letters,#,$or slashes. - Drop years and numbers right after "order", "#", "$", "invoice" and the like.
- Keep the candidate closest to a word like "code", up to about 60 characters before or 40 after.
In TypeScript, a lean version:
// Words that usually sit near the code, in English and Portuguese
const KEYWORDS = /(c[oó]digo|code|otp|pin|verifica\w*|confirma\w*|senha|password|token)/gi;
// Numbers right after these are orders, invoices or prices
const NOT_A_CODE_BEFORE = /(#|n[ºo°.]\s*|pedido|order|invoice|fatura|r\$|\$)\s*:?\s*$/i;
const CANDIDATE = /(?<![\w#$.\/-])(\d{3}[- ]\d{3}|\d{4,8})(?![\w\/%-])/g;
function findCode(text: string): string | null {
const clean = text.replace(/https?:\/\/\S+/g, " ");
let best: { code: string; distance: number } | null = null;
for (const match of clean.matchAll(CANDIDATE)) {
const start = match.index;
const end = start + match[1].length;
const before = clean.slice(Math.max(0, start - 60), start);
const after = clean.slice(end, end + 40);
if (/^(19|20)\d{2}$/.test(match[1]) || NOT_A_CODE_BEFORE.test(before)) continue;
const last = [...before.matchAll(KEYWORDS)].at(-1);
const next = after.search(KEYWORDS);
const distance = Math.min(
last ? before.length - (last.index + last[0].length) : Infinity,
next >= 0 ? next : Infinity,
);
if (distance === Infinity) continue;
if (!best || distance < best.distance) best = { code: match[1].replace(/[- ]/g, ""), distance };
}
// null when no number is near any word: better to fail than type the wrong number
return best?.code ?? null;
}
It handles most cases, but it's worth knowing what it misses: codes with letters, words in other languages, accents, and emails that say "use the number below" with the code three lines later.
On saci.cc, the code comes ready
saci.cc does this search when the email arrives, with a longer word list in English, Portuguese and Spanish, codes with letters like K7P2QX, prefixes like Google's G-482913, and the exceptions for orders, prices, phone numbers and years. If the code is in the subject, it's found there. The result shows up everywhere:
-
In the API: the
verificationCodefield comes in the inbox list and in each email, with the code ornull. "482-913" comes as482913, ready to type. -
In the npm package:
waitForCode()waits for the email and returns just the code. -
In MCP: the
get_verification_codetool does the same for AI agents. - On the site and in the extension: a button copies the code without opening the email.
import { createInbox } from "saci.cc";
const inbox = await createInbox();
// ...
// Waits for the email and returns just the code
const code = await inbox.waitForCode({ from: "your-app.com" });
// Or the whole email, with the code and link already extracted
const email = await inbox.waitForEmail({ subject: /code|código/i });
console.log(email.verificationCode, email.verificationLink);
If your app sends a "Confirm email" button instead of a code, the verificationLink field and waitForLink() do the same with the link. The post on confirmation links explains which links count.
When the code isn't found
If verificationCode is null on an email that has a code, it's usually because no word is near it. Two ways out:
- Improve the email: "Your verification code is 482913" helps saci.cc, and also people reading the email with a screen reader.
- Read the email's
textwithinbox.waitForEmail()and use your own regex, anchored on your template's fixed text.
And send feedback to oi@saci.cc or through the API with the email's text: cases like that become tests and improve the search for everyone.
In short
-
/\d{6}/picks up orders, years, prices and numbers in links, and is wrong without warning. - Look for the number closest to a word like "code", in the text with links removed, and drop years and orders.
- On saci.cc, use
verificationCode,waitForCode()orget_verification_codeand skip all that.
I build saci.cc, temporary email inboxes for end-to-end tests and AI agents. The npm package is saci.cc and the client is open source on GitHub.
來源:DEV Community · dev.to