Skip to content
MailSlurp logo

TOTP Testing: Automate Authenticator Enrollment and Login

Pair a virtual authenticator with your test user's enrollment secret, request a fresh TOTP code, and check enrollment, later login, expiry and replay.

A TOTP test completes the challenge normally handled by an authenticator app. It pairs with the secret issued to a test user, generates a time-based code, submits it to the application, and checks that the correct account becomes accessible.

Reading a code from a phone works for a manual check. It becomes awkward in CI, where several users may enroll at once and a code can expire while the browser is navigating. A fixed six-digit value cannot replace a code generated from the user's actual enrollment.

MailSlurp provides virtual TOTP authenticators that your test controls through an API. Your application supplies the enrollment secret; MailSlurp supplies codes from the paired device; Playwright, Selenium or another runner checks the application's response.

Choose the authenticator path

TOTP means time-based one-time password. An authenticator and the application derive a code from a shared secret and a time step. The TOTP standard, RFC 6238, describes that calculation and the need for time synchronization.

An email or SMS OTP is delivered in a message instead. Use the email OTP walkthrough or SMS OTP guide when your application sends the code. A TOTP test does not wait for incoming mail.

MFA requires independent factors. For a password-plus-authenticator flow, check that the password alone leaves the account protected and that the second factor completes the intended user's login. Generating a correctly formatted code is only the input to that test.

Pair with the test user's enrollment

Start with a dedicated user whose MFA enrollment you control. In the application's setup flow, obtain the manual Base32 secret or the otpauth:// URI represented by its QR code. Capture the value from that user's current enrollment, not a shared example secret.

Install mailslurp-client, set MAILSLURP_API_KEY in your test environment, and create a client:

import assert from "node:assert/strict";
import { MailSlurp } from "mailslurp-client";

const apiKey = process.env.MAILSLURP_API_KEY;
if (!apiKey) throw new Error("Set MAILSLURP_API_KEY");
const mailslurp = new MailSlurp({ apiKey });

The helper below accepts the enrollment URI and the browser action that uses it. It deletes only the virtual device it creates, including after a failed assertion. Your callback should submit the code and assert the application's enrollment or login result.

export async function withTestAuthenticator(
  client: MailSlurp,
  otpAuthUrl: string,
  run: (getCode: () => Promise<{ code: string; expiresAt?: Date | null }>) => Promise<void>,
) {
  const uri = new URL(otpAuthUrl);
  if (uri.protocol !== "otpauth:" || uri.hostname !== "totp") {
    throw new Error("Expected the test user's TOTP enrollment URI");
  }
  const device = await client.mfaController.createTotpDeviceForOtpAuthUrl({
    createTotpDeviceOtpAuthUrlOptions: { otpAuthUrl },
  });
  let runFailed = false;
  let runError: unknown;
  try {
    await run(async () => {
      const result = await client.mfaController.getTotpDeviceCode({
        id: device.id,
        minSecondsUntilExpire: 10,
      });
      assert.match(result.code, /^[0-9]+$/);
      return result;
    });
  } catch (error) {
    runFailed = true;
    runError = error;
  }
  try {
    await client.mfaController.deleteTotpDevice({ id: device.id });
  } catch (cleanupError) {
    if (runFailed) throw new AggregateError([runError, cleanupError], "Test and device cleanup failed");
    throw cleanupError;
  }
  if (runFailed) throw runError;
}

Call getCode() just before filling the authenticator input, and keep code as a string so leading zeros survive. minSecondsUntilExpire asks for time to submit the response; it does not extend the application's acceptance window. If a cleanup request fails, report it alongside the original test failure so the device can be removed.

If the application exposes a Base32 key instead, use createTotpDeviceForBase32SecretKey. Preserve its digit count, period and algorithm when those differ from defaults. The TOTP API documentation covers the pairing alternatives.

Prove a later login, not only enrollment

In the callback, first submit a fresh code to complete enrollment and check the application's confirmation. Then sign out, start a new login, enter the password, and confirm that protected account data is still unavailable while the second-factor challenge is open. Request a code from the same paired device, submit it, and assert the expected account identity.

Two requests within one time step can return the same code. If the identity provider rejects code reuse, wait until the first response's expiresAt has passed before requesting the login code. Budget for that transition in the test timeout. If expiry is not returned, use the provider's documented period and accepted window; do not assume another request necessarily gives a different value.

The Selenium Auth0 example demonstrates enrollment followed by a later sign-in. The Playwright Auth0 example covers browser enrollment. Adapt selectors and final account assertions to your application's actual screens.

Test rejection without relying on chance

Use separate controlled scenarios for the application's failure policies:

Scenario Useful assertion
Invalid code The challenge stays open and protected account data remains unavailable.
Code outside the accepted time window The application rejects it according to its configured clock-skew allowance.
Code already consumed Reuse follows the provider's documented replay policy.
New enrollment replaces an old device The new pairing works and the retired factor follows the removal policy.
Too many failed attempts The documented retry or lockout behavior occurs for the dedicated test user.

An arbitrary value such as 000000, or another user's generated code, can coincidentally be valid. In a controlled test environment, choose a value known to be outside the target user's accepted codes. Exercise lockout checks on disposable test users so another scenario is not unexpectedly locked out.

Diagnose the failed step

If pairing succeeds but the application rejects the code, compare the enrollment and user first. Next check algorithm, digits, period, clock synchronization, time remaining at submission and replay policy. Resetting MFA changes the pairing; keep the new device ID with the new enrollment.

A local TOTP implementation can test your own verifier against known vectors. Keep a separate end-to-end test through enrollment and the real challenge so changes in the identity provider or browser journey are also exercised.

Keep secrets, QR enrollment data and usable codes out of screenshots and shared logs. Record the test user reference, device ID and failed application assertion instead. Remove the application test user or its enrollment through your normal teardown; deleting the virtual MailSlurp device does not change the application's MFA settings.