Documentation: Handling Time-Based OTP with Testim and getTimeBasedCode Function

This guide explains how to retrieve and use Time-Based One-Time Passwords (TOTP) in Testim using the getTimeBasedCode function.

Purpose

The getTimeBasedCode function is designed to automate the retrieval of TOTP codes for a specified user and service. This is essential for automated tests requiring 2FA (two-factor authentication) based on time-sensitive codes, making it particularly useful for Testim-based end-to-end (E2E) testing.

Function Overview

The getTimeBasedCode function makes a request to an API endpoint to fetch the TOTP for a user. This function is parameterized by user and service identifiers and includes options for enhanced logging and authentication.

getTimeBasedCode Function Definition

const getTimeBasedCode = async (
  user: string,             // Identifier for the user in the TOTP service
  service: string,          // The service issuing the OTP
  options: { 
    verbose?: boolean,      // Optional flag for logging
    registeredKey: string   // Required key for API authentication
  }
): Promise<string> => { /* Implementation here */ }

Parameters

  • user: string - Represents the user label in the TOTP system, often corresponding to an account or email.
  • service: string - Represents the TOTP issuer (e.g., the application or service name).
  • options: object - Additional configuration options.
    • verbose: boolean (optional) - When true, enables logging to provide additional output, useful for debugging.
    • registeredKey: string - An authentication key required to access the TOTP API.

Return Value

The function returns a Promise that resolves to the OTP code (string) for the user:

// Example return value
"123456"

Using getTimeBasedCode in Testim

  1. Install the Function: Import the getTimeBasedCode function into your Testim project’s custom JavaScript code blocks to handle OTP retrieval.
  2. Set Environment Variables: Ensure API_BASE_URL is configured in your Testim environment settings to connect to the TOTP retrieval API.
  3. Invoke getTimeBasedCode in a Test Step: Use getTimeBasedCode in a Testim test step by providing the necessary parameters (user, service, and options). Here’s an example usage:
    const timeBasedOTP = async () => {
      try {
        const otpCode = await getTimeBasedCode("userLabel", "ServiceName", {
          verbose: true,
          registeredKey: "YOUR_REGISTERED_KEY"
        });
        
        console.log(`Retrieved Time-Based OTP: ${otpCode}`);
        return otpCode; // Use this OTP for the 2FA flow in your Testim test
      } catch (error) {
        console.error(`Failed to retrieve TOTP: ${error.message}`);
        throw error;
      }
    };
    
  4. Validate OTP in Testim: Use the retrieved OTP code in subsequent steps in Testim, such as entering it into a verification field to complete 2FA.

Example in Testim

Here’s a full example of using the retrieved OTP in a Testim test step:

await timeBasedOTP().then(code => {
  // Insert the OTP code into the OTP input field in Testim
  await testim.setValue({ selector: '#otp-input-field' }, code);
});

Error Handling

The function will raise errors if:

  • The API request fails or times out.
  • The registeredKey is invalid or missing.
  • The API responds with an error message.

Enable the verbose option to see detailed logs in the console for troubleshooting.

Important Notes

  • Environment Configuration: Ensure API_BASE_URL and registeredKey are securely configured in Testim.
  • API Rate Limits: Verify any rate limitations or quotas on the TOTP API.
  • Time Sensitivity: Since TOTPs are time-based, the code must be retrieved and entered within its valid time window (often 30 seconds).

Conclusion

Integrating getTimeBasedCode with Testim streamlines 2FA testing by automating TOTP retrieval, enabling efficient handling of time-based authentication in end-to-end tests. This approach enhances automation reliability, minimizing manual OTP entry for smooth 2FA workflows.

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