How to Test Otp Verification on Web (Complete Guide)
One-Time Password (OTP) verification is a critical security layer for many web applications, safeguarding user accounts and sensitive transactions. Ineffective OTP implementation directly impacts user
Robust OTP Verification Testing for Web Applications
One-Time Password (OTP) verification is a critical security layer for many web applications, safeguarding user accounts and sensitive transactions. Ineffective OTP implementation directly impacts user experience, leading to account lockouts, failed transactions, and a significant erosion of trust. Thorough testing of OTP flows is not optional; it's a foundational requirement for secure and reliable web services.
Common OTP Verification Pitfalls
Users encounter problems when OTP systems fail in several predictable ways:
- Expired OTPs: Codes sent but not used within their valid window.
- Invalid OTPs: Incorrect codes entered by the user or generated incorrectly by the system.
- Rate Limiting: Excessive resend attempts locking out legitimate users.
- Delivery Failures: OTPs not reaching the user's registered channel (email/SMS).
- Security Vulnerabilities: OTPs being predictable, bypassable, or exposed.
- Usability Issues: Clunky interfaces for entering OTPs, especially on mobile.
Comprehensive OTP Verification Test Cases
A robust testing strategy requires covering a range of scenarios.
#### Happy Path Scenarios
- Successful Verification:
- Action: User initiates OTP request, receives valid OTP, enters it correctly, and is successfully verified.
- Expected Outcome: User proceeds to the next step (e.g., dashboard, transaction completion).
- Resend OTP (Within Limit):
- Action: User requests an OTP, waits for it to expire or be invalid, and then successfully requests and uses a new OTP.
- Expected Outcome: User is verified with the second OTP.
- Auto-Submit OTP (if applicable):
- Action: User receives OTP via SMS/email, and the application auto-detects and submits it without manual input.
- Expected Outcome: Seamless verification.
#### Error Scenarios
- Invalid OTP Entry:
- Action: User enters an incorrect OTP.
- Expected Outcome: Clear error message indicating invalid OTP, with option to resend or try again.
- Expired OTP Entry:
- Action: User attempts to use an OTP after its validity period has passed.
- Expected Outcome: Error message indicating OTP has expired, with an option to resend.
- Exceeding Resend Limit:
- Action: User repeatedly requests OTPs beyond the allowed threshold.
- Expected Outcome: User is temporarily or permanently blocked from requesting further OTPs, with a clear notification about the lockout.
- No OTP Received:
- Action: User requests OTP but does not receive it within a reasonable timeframe.
- Expected Outcome: Application provides clear instructions on troubleshooting or contacting support. This may require manual checks of email/SMS gateways or logs.
- Special Characters/Empty Input:
- Action: User attempts to enter spaces, special characters, or leave the OTP field blank.
- Expected Outcome: Input validation prevents submission or displays an error message.
#### Edge Cases
- Simultaneous OTP Requests:
- Action: User initiates OTP requests from multiple devices or browsers concurrently for the same account.
- Expected Outcome: Only the most recent valid OTP should be accepted; older ones should be invalidated.
- Interruption During Verification:
- Action: User starts the OTP verification process, then navigates away or closes the tab/browser before completing.
- Expected Outcome: The session state should be handled gracefully, preventing unexpected behavior upon return or re-initiation.
#### Accessibility Considerations
- Screen Reader Compatibility:
- Action: Use a screen reader (e.g., NVDA, JAWS, VoiceOver) to navigate the OTP input field and verification process.
- Expected Outcome: All labels, instructions, error messages, and buttons are clearly announced. The OTP input field should be properly labeled.
- Keyboard Navigation:
- Action: Navigate and complete the OTP verification using only the keyboard (Tab, Shift+Tab, Enter, Spacebar).
- Expected Outcome: All interactive elements are focusable and operable via keyboard. Focus indicators are visible.
Manual Testing Approach for OTP Verification
- Scenario Setup: Ensure you have access to the user's registered email or phone number for receiving OTPs.
- Initiate OTP Request: Navigate to the page requiring OTP verification (e.g., login, password reset, payment confirmation). Click the "Send OTP" or equivalent button.
- Receive and Record OTP: Check the designated channel (email inbox, SMS app) for the OTP. Note the exact code and its validity period if displayed.
- Enter Valid OTP: Input the received OTP into the provided field and click "Verify" or "Submit."
- Observe: Confirm successful redirection or confirmation message.
- Test Invalid OTP: Repeat step 3, but enter a deliberately incorrect OTP.
- Observe: Verify the error message and the ability to retry or resend.
- Test Expired OTP: Wait for the OTP to expire (check its validity period). Attempt to enter the previously received OTP.
- Observe: Confirm the "expired" error message and resend option.
- Test Resend Functionality: After an OTP has expired or been invalidated, click the "Resend OTP" button.
- Observe: Confirm a new OTP is received and that it works. Note any cooldown timers for resending.
- Test Rate Limiting: Repeatedly click "Resend OTP" within a short period, exceeding the defined limit.
- Observe: Verify that the system blocks further requests and displays an appropriate message.
- Test Input Validation: Try entering non-numeric characters, spaces, or leaving the field empty.
- Observe: Confirm input restrictions and error handling.
- Accessibility Checks: Use a screen reader and keyboard-only navigation to perform the key steps of the OTP flow.
- Observe: Listen for clear audio cues and ensure all elements are reachable and operable.
Automated Testing for Web OTP Verification
Automating OTP verification presents a unique challenge: receiving the OTP.
- Tools: Playwright and Selenium are excellent choices for web UI automation.
- Receiving OTPs Programmatically:
- SMS Gateway Services: Services like Twilio, Nexmo (Vonage), or AWS SNS can be integrated. Your test script can make an API call to these services to retrieve the latest SMS received by a specific test number.
- Email Testing Services: Services like Mailtrap.io, Ethereal.email, or dedicated testing email accounts with IMAP/POP3 access allow your scripts to fetch emails.
- Mocking OTPs (for development/unit testing): In some environments, you might mock the OTP generation/delivery to bypass the external dependency during early testing phases.
Example (Conceptual Playwright - fetching from Mailtrap.io):
// Requires a Mailtrap client library and configuration
const { MailtrapClient } = require('mailtrap');
const client = new MailtrapClient({ token: 'YOUR_MAILTRAP_TOKEN' });
async function getLatestOtp(emailAddress) {
try {
const inbox = await client.getInbox('YOUR_INBOX_ID'); // Get your specific inbox ID
const messages = await inbox.getMessages({ limit: 1, from: 'no-reply@yourdomain.com' }); // Filter by sender
if (messages.length > 0) {
const emailBody = messages[0].text_content || messages[0].html;
// Regex to extract OTP (adjust based on your email format)
const otpMatch = emailBody.match(/Your verification code is: (\d{6})/);
if (otpMatch && otpMatch[1]) {
return otpMatch[1];
}
}
} catch (error) {
console.error("Error fetching OTP from Mailtrap:", error);
}
return null;
}
// In your test:
const page = await browser.newPage();
await page.goto('https://your-app.com/login');
await page.click('button:has-text("Send OTP")');
let otp = null;
for (let i = 0; i < 10; i++) { // Retry fetching for a few seconds
otp = await getLatestOtp('testuser@example.com');
if (otp) break;
await page.waitForTimeout(2000); // Wait 2 seconds before retrying
}
if (otp) {
await page.fill('input[name="otp"]', otp);
await page.click('button:has-text("Verify")');
// Assert successful login/verification
} else {
throw new Error("Failed to retrieve OTP");
}
SUSA's Autonomous OTP Verification Testing
SUSA automates OTP verification testing by integrating with these underlying mechanisms and leveraging its persona-driven exploration.
- Autonomous Exploration: SUSA uploads your APK or web URL and begins exploring the application's flows, including any identified OTP entry points. It doesn't require pre-written scripts for the OTP flow itself.
- Persona-Based Testing:
- Curious/Novice/Teenager: These personas will naturally attempt to enter incorrect OTPs, or try to proceed without entering one, to see what happens. They might also try to resend OTPs rapidly, triggering rate limiting tests.
- Impatient: This persona might try to submit an OTP immediately after requesting it, before it has a chance to arrive, testing the system's response to potentially expired or not-yet-received codes.
- Adversarial: This persona is specifically designed to probe for security weaknesses. They will attempt to bypass OTP verification, test for injection vulnerabilities in the OTP field, or try to exploit race conditions if multiple OTPs are requested.
- Power User: Might attempt to use special characters, long codes, or rapid resends to uncover input validation or rate-limiting flaws.
- Accessibility Persona: SUSA's accessibility engine automatically checks for WCAG 2.1 AA compliance, including proper ARIA attributes for OTP fields, clear labeling, and keyboard operability.
- Finding Issues: SUSA identifies:
- Crashes/ANRs: If the OTP submission process causes an application crash.
- Dead Buttons: If the "Verify" button becomes unresponsive after incorrect input.
- UX Friction: If error messages are unclear, or the process is overly complicated
Test Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free