How to test SMS OTP codes in Cypress
Cypress can't receive a text message, but cy.request can call any API. That's all you need to test SMS codes with a real number.
Step 1: custom commands
Add these to cypress/support/commands.js. Put your API key in cypress.env.json as QI_KEY (and keep that file out of 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);
});
});Step 2: the test
// 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');
});
});
});Recording the existing message ids first (seen) makes sure the test only accepts a code that arrived after it pressed "Send code".
Tips
- Run SMS specs on one machine at a time if all of them share one number.
- Thirty tries three seconds apart gives about 90 seconds, which covers slow deliveries.
- Email codes too? See email testing in Cypress.
Related guides
- How to test SMS 2FA in Selenium with Python
- How to test Twilio Verify and OTP flows end to end
- How to test phone verification in mobile apps with Appium
- A US phone number for SMS testing
- SMS testing overview
Get a test number: every paid QuickInbox plan includes a real US phone number and a monthly SMS allowance, with plans from $9 a month. Extra packs start at $5 a month. See SMS testing and pricing.