Cypress में SMS OTP कोड कैसे टेस्ट करें

· 5 मिनट में पढ़ें · QuickInbox टीम

  • Cypress
  • SMS
  • OTP

Cypress टेक्स्ट मैसेज नहीं पा सकता, लेकिन cy.request कोई भी API कॉल कर सकता है। असली नंबर से SMS कोड टेस्ट करने के लिए बस इतना ही चाहिए।

स्टेप 1: custom commands

इन्हें cypress/support/commands.js में जोड़ें। अपनी API key को cypress.env.json में QI_KEY के रूप में रखें (और उस फ़ाइल को 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) पक्का करता है कि टेस्ट सिर्फ़ वही कोड माने जो "Send code" दबाने के बाद आया।

टिप्स

  • अगर सभी SMS specs एक नंबर शेयर करते हैं, तो उन्हें एक समय में एक ही मशीन पर चलाएँ।
  • तीन-तीन सेकंड के अंतर पर तीस कोशिशें लगभग 90 सेकंड देती हैं, जो धीमी डिलीवरी भी कवर करता है।
  • ईमेल कोड भी? देखें Cypress में ईमेल टेस्टिंग।

इससे जुड़ी गाइड

टेस्ट नंबर पाएँ: QuickInbox के हर पेड प्लान में एक असली US फ़ोन नंबर और हर महीने SMS की तय मात्रा शामिल है, प्लान $9 प्रति माह से। अतिरिक्त पैक $5 प्रति माह से। देखें SMS टेस्टिंग और प्राइसिंग।

← सभी लेख