如何在 Cypress 中测试短信 OTP 验证码
Cypress 收不到短信,但 cy.request 可以调用任何 API。用真实号码测试短信验证码,这就够了。
第 1 步:自定义命令
把这些加到 cypress/support/commands.js。把 API 密钥作为 QI_KEY 放进 cypress.env.json(并且不要把这个文件提交到 git)。
// cypress/support/commands.js
const BASE = 'https://business.quickinbox.net';
const auth = () => ({ 'X-API-Key': Cypress.env('QI_KEY') });
// Yields { number, seen }: your test number and the ids of texts it already has.
Cypress.Commands.add('smsNumber', () => {
return cy.request({ url: `${BASE}/api/business/sms/numbers`, headers: auth() })
.its('body.numbers.0')
.then((number) =>
cy.request({ url: `${BASE}/api/business/sms/numbers/${number.id}/messages`, headers: auth() })
.then((res) => ({ number, seen: res.body.messages.map((m) => m.id) })));
});
// Polls until a new text with a code arrives, then yields the code.
Cypress.Commands.add('waitForSmsCode', (numberId, seen, tries = 30) => {
return cy.request({ url: `${BASE}/api/business/sms/numbers/${numberId}/messages`, headers: auth() })
.then((res) => {
const hit = res.body.messages.find((m) => !seen.includes(m.id) && /\b\d{4,8}\b/.test(m.body));
if (hit) return hit.body.match(/\b(\d{4,8})\b/)[1];
if (tries <= 1) throw new Error('No new SMS code arrived');
cy.wait(3000);
return cy.waitForSmsCode(numberId, seen, tries - 1);
});
});第 2 步:测试
// cypress/e2e/phone-verify.cy.js
it('verifies the phone number with a real SMS code', () => {
cy.smsNumber().then(({ number, seen }) => {
cy.visit('/settings/phone');
cy.get('input[name=phone]').type(number.phone_number);
cy.contains('button', 'Send code').click();
cy.waitForSmsCode(number.id, seen).then((code) => {
cy.get('input[name=code]').type(code);
cy.contains('button', 'Verify').click();
cy.contains('Phone number verified').should('be.visible');
});
});
});先记录已有短信的 id(seen),确保测试只接受在点击“发送验证码”之后到达的验证码。
小技巧
- 如果所有短信测试共用一个号码,一次只在一台机器上运行它们。
- 每隔三秒试一次、共三十次,大约 90 秒,足以应对慢速送达。
- 还要测邮件验证码?参见 Cypress 中的邮件测试。
相关指南
- 如何用 Python 在 Selenium 中测试短信 2FA
- 如何端到端测试 Twilio Verify 和 OTP 流程
- 如何用 Appium 测试移动应用中的手机验证
- 用于短信测试的美国手机号码
- 短信测试概览
获取测试号码:每个 QuickInbox 付费套餐都包含一个真实的美国手机号码和每月短信额度,套餐每月 $9 起。额外短信包每月 $5 起。参见短信测试和价格。