Documentation: Retrieving OTP Sent by Email with Cypress

This guide explains how to retrieve a One-Time Password (OTP) sent by email within a Cypress test environment. The otp-device-sync service allows you to retrieve email-based OTPs either through an HTTP API request or via the otp-device-sync JavaScript library. Each approach has specific benefits; the choice depends on your testing setup and preferences.

Choosing Between HTTP API and JavaScript Library

  1. HTTP API
    • Best For: Test environments where minimizing additional dependencies is preferred or where tests frequently utilize HTTP requests directly.
    • Advantages:
      • Direct integration with Cypress using cy.request, minimizing setup.
      • Easily configurable for handling responses and timeout with Cypress' native features.
    • Usage: Sends an HTTP request to retrieve the OTP email content.
  2. JavaScript Library
    • Best For: Scenarios where a streamlined, programmatic approach is desired, especially if your tests already use otp-device-sync.
    • Advantages:
      • Provides a ready-to-use function, handling request setup and error management.
      • Offers verbose logging, useful for debugging.
      • Reduces repetitive code by encapsulating the API call in a function.
    • Usage: Import and use the getMailComponents function to retrieve the OTP email content.

Option 1: Using the HTTP API in Cypress

Example Code

Cypress.Commands.add('getEmailOTP', (userEmail, senderEmail, registeredKey) => {
  const API_BASE_URL = Cypress.env('API_BASE_URL');

  return cy.request({
    method: 'GET',
    url: `${API_BASE_URL}/retrieve/email`,
    qs: {
      user: userEmail,
      service: senderEmail,
      registeredKey,
    },
    failOnStatusCode: false,
    timeout: 300000 // 5 minutes
  }).then((response) => {
    if (response.status === 200) {
      const { code, text, html } = response.body;
      cy.log(`Retrieved Email OTP: ${code}`);
      return { code, text, html };
    } else {
      throw new Error(`Error retrieving Email OTP: ${response.body}`);
    }
  });
});

// Usage in a Cypress test
cy.getEmailOTP("user@example.com", "sender@example.com", "YOUR_REGISTERED_KEY").then((otpData) => {
  cy.log(`OTP Code: ${otpData.code}`);
  cy.log(`Email Text: ${otpData.text}`);
  cy.log(`Email HTML: ${otpData.html}`);
});

Option 2: Using the JavaScript Library in Cypress

Setup

  1. Install the Library:
    • Run npm install otp-device-sync in your project directory to add the library to Cypress.
  2. Import and Use the Function:
    • Use getMailComponents to retrieve the email OTP directly within your Cypress test.

Example Code

import { getMailComponents } from 'otp-device-sync';

Cypress.Commands.add('getEmailOTP', (userEmail, senderEmail, registeredKey) => {
  return getMailComponents(userEmail, senderEmail, { registeredKey, timeout: 300000, verbose: true })
    .then((data) => {
      cy.log(`Retrieved Email OTP: ${data.code}`);
      return data;  // { code, text, html }
    })
    .catch((error) => {
      throw new Error(`Error retrieving Email OTP: ${error.message}`);
    });
});

// Usage in a Cypress test
cy.getEmailOTP("user@example.com", "sender@example.com", "YOUR_REGISTERED_KEY").then((otpData) => {
  cy.log(`OTP Code: ${otpData.code}`);
  cy.log(`Email Text: ${otpData.text}`);
  cy.log(`Email HTML: ${otpData.html}`);
});

Key Points

  • HTTP API:
    • Great for lightweight setups and when you prefer direct Cypress command chain integration.
    • Allows native Cypress handling of response parameters and timeout settings.
  • JavaScript Library:
    • Simplifies code with a prebuilt function, encapsulating API request setup and response handling.
    • Verbose logging and structured error handling simplify debugging.

Conclusion

Choose the HTTP API if you prefer minimal dependencies and want full control within Cypress over request parameters. Use the JavaScript library if you prefer an encapsulated, programmatic approach with built-in options. Both methods allow you to efficiently retrieve OTPs sent by email, automating 2FA flows within your Cypress test suite.

Price
Usage is free for the first three months of a (Service, User) pair and a small scale usage. For intensive use or use exceeding 3 months, you will be required to make a payment.
Security concerns
This tool is provided for testing purposes only and should not be used in production.
Legal and support
This solution is maintained by Litee Solutions, 14 rue Beffroy, 92200 Neuilly-sur-Seine, France. The email and SMS services provided are the property of Litee Solutions. Messages received through OTP Device Sync are deleted seconds after being processed. There is no user tracking; only the information necessary for proper functioning and billing is stored. For support, please send an email to: support@otp-device-sync.net