Quality Assurance·

How to E2E Test Login, 2FA, Magic Links and Email Verification

How to E2E test login flows with 2FA, authenticator codes, magic links, email verification and SMS codes, without turning security off or mocking the login.

QA.tech

A brass key in a frosted acrylic padlock with a gunmetal combination dial, representing a login protected by a second authentication factor.

Almost every end-to-end test starts behind a login, and modern logins rarely stop at a password. There's a code from an authenticator app, a magic link in an email, an SMS code or a verification email after sign-up. Each one is a step an automated test can't complete without help.

Teams usually respond by switching security off in test environments or mocking the login. Both mean the login itself, one of the journeys that matters most, never gets tested. This guide covers how to test each method for real.

First, split two problems

Getting logged in so other tests can run. Most tests don't care how the user logged in. They need a session. Log in once, save the session and reuse it.

Testing the login itself. A few tests should go through the full flow, including the second factor, because that's the journey under test.

Mixing the two is how suites end up with 300 tests that each type a password and a 2FA code, all failing together when the login page changes.

Log in once, reuse the session

In Playwright, a setup project logs in and saves cookies and local storage to a file. Other tests start already logged in. The Playwright authentication docs describe the pattern:

// auth.setup.ts
import { test as setup } from '@playwright/test';

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!);
  await page.getByRole('button', { name: 'Log in' }).click();
  await page.waitForURL('/dashboard');
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

Keep the saved file out of version control, since it holds a live session. For tests that change server-side state, use one account per parallel worker so they don't trip over each other. Logging in once per worker also keeps you under your identity provider's rate limits, which parallel testing can otherwise hit within seconds.

Testing 2FA with authenticator app codes (TOTP)

Authenticator apps generate time-based one-time passwords, defined in RFC 6238 (May 2011). The app and the server share a secret. Each computes a code from that secret and the current time, usually in 30-second steps. If they match, you're in.

That makes TOTP the easiest second factor to automate. Your test only needs the shared secret:

  1. Create a dedicated test account and enrol it in 2FA.
  2. When the enrolment screen shows the QR code, also copy the setup key, or the otpauth:// URI the QR code encodes. It contains the secret.
  3. Store the secret in your CI secrets, like a password.
  4. In the test, generate the current code with a library such as otplib for Node or pyotp for Python, and type it in.
import { generate } from 'otplib'; // v13 API; v12 used authenticator.generate(secret)

const code = await generate({ secret: process.env.TEST_USER_TOTP_SECRET! });
await page.getByLabel('Authentication code').fill(code);

Two things trip people up. CI runners with a drifting clock produce wrong codes, so make sure time sync is on. And if a test types a code right at the end of a 30-second window, it may expire before submission. Most servers accept the previous step too, but a retry that generates a fresh code is a cheap safety net.

Sign-up confirmations, email codes, magic links and password resets all need the test to read an email. Three ways to get it:

  • A test inbox service. Mailosaur, MailSlurp and similar tools give you addresses whose messages you can fetch through an API. The test waits for the email, extracts the link or code, and continues.
  • A local mail catcher. Mailpit or MailHog catches outgoing mail in development and preview environments and exposes it over HTTP. Good for previews, though it won't tell you whether your real email provider delivers.
  • Your auth provider's test mode. Some providers skip sending entirely for reserved addresses. Clerk's test mode, for example, accepts the fixed code 424242 for any address with the +clerk_test subaddress.

Test mode is fine for the "get logged in" problem and wrong for the "test the login" problem, because it skips the email you're trying to test. As of October 2026, Clerk no longer sends any email to +clerk_test addresses while test mode is on, so tests that need to follow a real link must use a real inbox.

For magic links specifically, also test that the link only works once and expires on time. Those are the security properties that matter, and the happy path doesn't check them.

Testing SMS codes

SMS is the hardest. Options:

  • Your provider's test numbers. Firebase and Google Cloud Identity Platform let you register test phone numbers with a fixed code, and no SMS is sent. Clerk treats fictional numbers in the 555-0100 to 555-0199 range as test numbers in test mode.
  • A real number you control. Rent a number from an SMS provider and read incoming messages through its API. This tests the real delivery path, at the cost of a few cents per message and occasional carrier delays.
  • A bypass in non-production environments. A fixed code accepted only when an environment variable is set. Quick, but make sure it can never be enabled in production.

Testing logins behind SSO, BankID and CAPTCHA

Single sign-on. Most identity providers let you create test users in a separate tenant or development instance. Test against that, and keep one or two tests that go through the full redirect to your real provider.

National eID such as BankID. These require a real person with a device. In test environments you'll need the provider's test mode or a stub. A Nordic lending marketplace on one of our calls was blocked on automating its main journeys until it set one up.

CAPTCHA. It exists to stop automation, so don't try to solve it. Disable it in test environments, allowlist your test runner's IP addresses, or use the provider's test keys: reCAPTCHA, hCaptcha and Turnstile all publish keys that always pass.

Preview environments behind a login wall

Pull request previews are often protected so the public can't see unreleased work. Your tests then hit the hosting platform's login before your own. Vercel, Netlify and others offer bypass tokens or headers for automation. Our guide to Vercel protection bypass for automated testing walks through the Vercel version.

Test accounts and secrets

  • Use dedicated test accounts, never a real person's login.
  • One account per role you test: admin, member, viewer, billing owner.
  • Keep credentials and TOTP secrets in a secrets manager or CI secrets.
  • Rotate them like any other credential.
  • In production, flag test accounts so they're excluded from analytics and emails.

Why not just mock the login?

Because the login is a journey your customers take every day, and when it breaks, nothing else matters. Daniel Mauno Pettersson, our co-founder and CEO, includes 2FA, email and SMS among the things you should be able to test without mocking, alongside journeys that cross apps. Mock it in unit tests if you like. In E2E tests, at least the critical login paths should run for real.

Where QA.tech fits

QA.tech, an AI testing platform, can't get past CAPTCHA, so it has to be disabled or bypassed in test environments. BankID needs a stub. Google sign-in can't be automated because Google's bot detection blocks it, so an app that only offers Google login needs a test-environment bypass or a separate test login. Credentials are stored as configs, unencrypted, and passed to the model during runs, so they should belong to dedicated test accounts.

For the rest, the agent handles the second factor itself. It logs in with email and password, email one-time codes, magic links, API keys and SMS codes through a leased number. For authenticator apps you paste the otpauth:// URI into the config, and the agent generates the current code when the login asks for it. When dozens of tests run in parallel, the docs cover how to stay inside your identity provider's rate limits.

FAQ

How do you automate 2FA in end-to-end tests? For authenticator app codes, store the TOTP secret from the test account's enrolment and generate the current code in the test with a library such as otplib or pyotp. For email or SMS codes, use a test inbox or test phone number you can read through an API.

Can Playwright handle two-factor authentication? Yes. Playwright drives the browser, and your test code generates or fetches the code: a TOTP library for authenticator apps, or an inbox or SMS API for emailed and texted codes. Save the logged-in state afterwards so other tests don't repeat the login.

How do you test magic link login? Send the magic link to an inbox your test can read through an API, extract the link, open it in the browser and check the user is logged in. Also check the link fails a second time and after it expires.

How do you test email verification in E2E tests? Sign up with an address from a test inbox service or a local mail catcher, wait for the verification email through its API, follow the link and check the account is marked as verified.

Should you disable 2FA in test environments? Not for the tests that check login. Disabling it means the most important security journey is never tested. Use dedicated test accounts with 2FA enabled, and reuse saved sessions for tests that don't need to log in.

How do you handle CAPTCHA in automated tests? Turn it off in test environments, allowlist your test runners, or use the CAPTCHA provider's published test keys. Don't try to solve it automatically.

Your team moves fast. Can your testing keep up?

Our QA agents test your product autonomously, so moving fast never means shipping broken. Start free or get a 30-minute demo.