Article featured image

End-to-end password reset testing with Selenium

20min readLast updated: February 27, 2026

Updated: November 2026

Testing password reset with Selenium end-to-end involves creating a test account with a unique email address, requesting a password reset, receiving the reset email through an email testing API, clicking the reset link in the same browser and setting a new password, and finally ensuring that you can log in with the new password and not with the old one. On top of the happy path, there are lots of ways that password reset should fail: clicking the link a second time, clicking an older link after a newer one has been sent, using an expired link, requesting a password reset for an email address that doesn’t belong to any account.

In this post, we’ll show you the different password reset test cases you should test (happy path, unhappy path, security, edge cases), what the password reset email should look like, and how to write end-to-end password reset tests with Selenium WebDriver in JavaScript. This includes testing that the reset link can’t be pointed at another host, which is often forgotten. To receive emails, we’ll use testmail.app. Every email address under your testmail.app namespace is an email inbox, and you can use one API request to wait for the email to arrive.

Password reset test cases

There’s only one way for password reset to work, and lots of ways for it to fail. The security test cases are from the OWASP Forgot Password Cheat Sheet. The last column says where each one is covered.

TypeTest caseExpected resultCovered by
PositiveRequest a reset for a registered addressThe reset email arrives within your target, for example 30 secondsSuite: every test
PositiveRead the reset email itselfA clear subject, your usual sender, one link, the expiry stated, and no passwordSuite: sends one link
PositiveOpen the link and set a valid new passwordThe password changes and the user can log in with itSuite: sets a new password
PositiveLog in with the old password afterwardsRejectedSuite: sets a new password
PositiveAfter the changeA "your password was changed" email arrives, with no password in itSuite: sets a new password
NegativePassword and confirmation don't matchA clear error, and nothing changesSelenium, form validation
NegativeNew password breaks the password policyA validation message; the same link still works for a valid passwordSelenium, form validation
NegativeSubmit the request form empty, or with a malformed addressA validation message, and no email sentSelenium, form validation
SecurityReset for an address with no accountThe same message as for a known address, in about the same timeSuite: answers the same
SecurityThe same link used twiceThe second use is rejectedSuite: works only once
SecurityTwo requests in a rowOnly the newest link worksSuite: accepts only the newest link
SecurityA link used after its lifetimeRejected, with a way to request a new oneSuite: rejects an expired link
SecurityA tampered or truncated token in the linkRejected, the same way as an expired linkSelenium: edit the link before opening it
SecurityA request with a forged X-Forwarded-Host or Host headerThe link still points at your real domain, over HTTPSSuite: builds the link from the real host
SecurityAnother account's ID or email swapped into the request that sets the passwordOnly the account the token belongs to changesAPI test
SecurityMany requests for one account or from one IPRate limited, without revealing whether the account existsAPI test
SecurityBefore the link is usedThe account is unchanged: no lockout, and the old password still worksAdd a login before setPassword()
SecurityOther sessions after a resetSigned out, or the user is asked whether to sign them outSelenium, two browser sessions
SecurityThe reset pageSends Referrer-Policy: no-referrer, so the token can't leak to other sitesAdd-on test after the suite
Edge caseAddress typed in different case or with spacesFinds the same accountSelenium, form input
Edge caseLink opened in another browser or deviceWorks, unless your app deliberately requires the same browserSelenium, a second driver
Edge caseAfter the resetThe user signs in normally; OWASP advises against logging them in automaticallySuite: sets a new password

What a password reset email should include

A user that receives a password reset email is locked out of their account and just wants to get back in. A phishing email may look similar, so the password reset email should be short, to the point, and obviously from your service. Here’s what it should include (and what your tests should check for, as the suite’s “sends one link” test checks most of these):

Example of a password reset email
Example of a password reset email
An example reset email from a fictional Acme, with each element the table below checks

Here’s an example of a password reset email from the fictional company Acme, with each element from the table below:

IncludeWhy it mattersHow a test checks it
A subject that says what it is, such as "Reset your Acme password"It shouldn't look like an alert or a promotionassert.match(email.subject, /reset/i)
Your usual sender name and addressAn unfamiliar sender makes a genuine reset look like phishingMatch email.from against your sending address
One reset link or button, and nothing competing with itExtra links and offers get in the way of the one thing the user came to doExactly one distinct /reset-password URL in the HTML
A link to your own domain, over HTTPSThe token in the link is a key to the accountThe link's origin is your app's, even when the request carried a forged host header
How long the link lasts, and that it works onceIt tells the user to act now and explains a dead link laterThe plain text mentions the expiry, for example /expire/i
What to do if they didn't ask for it"You can ignore this email; your password won't change," plus a way to reach supportMatch that wording in the plain text
No password, old or newOWASP's advice is to send a link or code, never a passwordNeither the HTML nor the text contains the test account's password
A plain-text partSome people and mail clients only show plain text, and it's simpler to assert onemail.text is present

Once the user’s password has been changed, send them another email alerting them that their password was changed. As above, it should say what changed, when it happened, and what to do if it wasn’t them. It shouldn’t include their password. OWASP also recommends sending this email, and the suite’s first test waits for it.

If your password reset flow sends a code instead of a link, the same recommendations apply. See the email OTP testing guide for details on testing OTPs sent by email. For recommendations on sending transactional emails like password reset emails well (authentication, sender reputation, templates), see Transactional emails: a complete guide.

How the end-to-end test works

Selenium can control a web browser, but can’t receive emails. That’s why we’ll combine it with testmail.app’s JSON API. Here’s how each test works, in five steps:

  1. Generate an email address. We’ll use testmail.app’s API to wait for emails to arrive at {namespace}.{tag}@inbox.testmail.app. Any tag will work without needing to create it first, so tests can generate their own unique email addresses and won’t conflict with each other if you run tests in parallel or retry them.
  2. Create a new user with that email address (with whatever test setup code you already have), so there’s a real account to reset.
  3. Request a password reset from the browser, and note the confirmation message.
  4. Use testmail.app’s API to wait for the email to arrive. We pass livequery=true so that testmail.app waits for an email to arrive before responding. We also pass timestamp_from so that it ignores emails that arrived before that time. This way, we don’t need to repeatedly check if the email has arrived or add arbitrary sleeps to our tests.
  5. Open the password reset link in the same browser and set a new password. Log in with the new password and ensure it works, and try to log in with the old password and ensure it doesn’t.
One password reset test across Mocha, Chrome, your app and testmail.app

One password reset test across Mocha, Chrome, your app and testmail.app

Some of the unhappy path tests follow similar steps, but either click the link twice, click an old link after a new one has been sent, wait for the link to expire, or request a password reset for an email address that doesn’t belong to a user.

When Selenium fits, and when an HTTP request is enough

We’ve used Selenium for anything that involves the user interface (requesting a password reset, setting a new password, logging in), but you can make some assertions more easily with HTTP requests, so we’ve included examples of that too. You can’t easily set arbitrary request headers in Selenium, so we used fetch in Node.js to test that the password reset link can’t be pointed at another host. You could also test rate limiting or response headers (such as Referrer-Policy) this way.

Setup

To follow along, you’ll need:

  • Node.js 22.23.4+ (22 line), 24.22.1+, or 26.12.1+ (what selenium-webdriver 4.52 supports) and Chrome.
  • A testmail.app namespace and API key. The free plan limits you to 100 emails per month. The whole test suite sends around ten emails, so you can run it a handful of times per month for free. If you want to run these tests in CI on every push, get yourself a paid plan.
  • A test environment of your application that sends real emails, and some way to create users in it from tests (could be a seed script or an admin API or something else). The suite’s createAccount() calls a placeholder endpoint; swap in your own setup.

Install selenium-webdriver and Mocha:

npm install --save-dev selenium-webdriver mocha

Then configure environment variables:

export TESTMAIL_APIKEY=your-api-key
export TESTMAIL_NAMESPACE=your-namespace
export BASE_URL=https://staging.yourapp.com

Note: you don’t need to install the chromedriver package. selenium-webdriver has Selenium Manager that will attempt to find chromedriver on your machine. If it’s not present it will download a driver that matches your Chrome. It will always prefer chromedriver found on your PATH even if it’s an older version (more on that in Troubleshooting).

The suite assumes these pages and names; change them to match your app:

StepWhat the suite looks for
Forgot-password page/forgot-password, with an email field and a submit button
Confirmation after the requestAn element with role="status"
Reset link in the emailA URL containing /reset-password
New-password pagepassword and confirmPassword fields
After a successful resetA redirect to /login
After logging inA URL containing /dashboard
Errors (a bad login, a dead link)An element with role="alert"

The status and alert roles are useful for screen readers as they will read out the status and alert messages, and they give tests a stable selector.

The Selenium test suite

Create a file test/password-reset.test.mjs with the following contents. This test suite uses fetch and assert that ship with Node.js. So the only dependencies you need are selenium-webdriver and Mocha.

// test/password-reset.test.mjs (run with: npx mocha test/password-reset.test.mjs)
import assert from 'node:assert/strict';
import webdriver from 'selenium-webdriver';
import chrome from 'selenium-webdriver/chrome.js';

const { Builder, By, until } = webdriver;
const API = 'https://api.testmail.app/api/json';
const { TESTMAIL_APIKEY, TESTMAIL_NAMESPACE, BASE_URL = 'http://localhost:3000' } = process.env;
const OLD_PASSWORD = 'correct horse battery staple';
const NEW_PASSWORD = 'a brand new passphrase';

/** One testmail.app inbox per test: {namespace}.{tag}@inbox.testmail.app */
class Inbox {
  constructor(prefix = 'reset') {
    this.tag = `${prefix}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
    this.address = `${TESTMAIL_NAMESPACE}.${this.tag}@inbox.testmail.app`;
    this.since = Date.now();
  }

  /** Waits on testmail.app's side for the next email to this inbox. */
  async next() {
    const params = new URLSearchParams({
      apikey: TESTMAIL_APIKEY,
      namespace: TESTMAIL_NAMESPACE,
      tag: this.tag,
      timestamp_from: String(this.since),
      livequery: 'true',
    });
    const res = await fetch(`${API}?${params}`, { signal: AbortSignal.timeout(85_000) });
    const body = await res.json();
    if (body.result !== 'success') throw new Error(`testmail.app: ${body.message}`);
    const email = body.emails.at(-1); // newest first, so the last one is the oldest new email
    this.since = email.timestamp + 1; // the next call waits for a newer one
    return email;
  }
}

/** Every link in the email's HTML, with & decoded the way a mail client would. */
const links = (email) => [...email.html.matchAll(/href="([^"]+)"/g)].map((match) => match[1].replaceAll('&', '&'));

function resetLink(email) {
  const href = links(email).find((url) => url.includes('/reset-password'));
  assert.ok(href, `no reset link in "${email.subject}"`);
  return href;
}

// Placeholder: however your test setup creates a user (a seed script, an admin API or a signup call)
async function createAccount(email, password) {
  const res = await fetch(`${BASE_URL}/api/test/users`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  assert.ok(res.ok, `creating the account returned ${res.status}`);
}

describe('password reset', function () {
  this.timeout(120_000); // each test waits for at least one email
  let driver;

  beforeEach(async function () {
    const options = new chrome.Options();
    options.addArguments('--headless=new');
    // Selenium Manager finds or downloads a chromedriver that matches your Chrome
    driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();
  });

  afterEach(async function () {
    await driver?.quit();
  });

  async function requestReset(address) {
    await driver.get(`${BASE_URL}/forgot-password`);
    await driver.findElement(By.name('email')).sendKeys(address);
    await driver.findElement(By.css('button[type=submit]')).click();
    const notice = await driver.wait(until.elementLocated(By.css('[role=status]')), 10_000);
    return notice.getText();
  }

  async function setPassword(link, password) {
    await driver.get(link);
    await driver.wait(until.elementLocated(By.name('password')), 10_000).sendKeys(password);
    await driver.findElement(By.name('confirmPassword')).sendKeys(password);
    await driver.findElement(By.css('button[type=submit]')).click();
    await driver.wait(until.urlContains('/login'), 10_000); // a finished reset sends the user to log in, not straight in
  }

  async function logIn(address, password) {
    await driver.manage().deleteAllCookies();
    await driver.get(`${BASE_URL}/login`);
    await driver.findElement(By.name('email')).sendKeys(address);
    await driver.findElement(By.name('password')).sendKeys(password);
    await driver.findElement(By.css('button[type=submit]')).click();
  }

  it('sets a new password, and the old one stops working', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    await setPassword(resetLink(await inbox.next()), NEW_PASSWORD);

    const notice = await inbox.next(); // the "your password was changed" email
    assert.match(notice.subject, /changed/i);
    assert.ok(!`${notice.html} ${notice.text}`.includes(NEW_PASSWORD), 'the notice contains the password');

    await logIn(inbox.address, NEW_PASSWORD);
    await driver.wait(until.urlContains('/dashboard'), 10_000);
    await logIn(inbox.address, OLD_PASSWORD);
    await driver.wait(until.elementLocated(By.css('[role=alert]')), 10_000);
  });

  it('sends one link, states the expiry, and no password', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    const email = await inbox.next();

    assert.match(email.subject, /reset/i);
    assert.match(email.from, /no-reply@example\.com/); // the address you send from
    assert.equal(new Set(links(email).filter((url) => url.includes('/reset-password'))).size, 1);
    assert.ok(email.text, 'no plain-text part');
    assert.match(email.text, /expire/i);
    assert.ok(!`${email.html} ${email.text}`.includes(OLD_PASSWORD), 'the email contains the password');
  });

  it('works only once', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    const link = resetLink(await inbox.next());

    await setPassword(link, NEW_PASSWORD);
    await driver.get(link); // the same link again
    const alert = await driver.wait(until.elementLocated(By.css('[role=alert]')), 10_000);
    assert.match(await alert.getText(), /expired|invalid|already used/i);
  });

  it('accepts only the newest link', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    const first = resetLink(await inbox.next());
    await requestReset(inbox.address);
    const second = resetLink(await inbox.next()); // waits for the newer email
    assert.notEqual(second, first);

    await driver.get(first);
    const alert = await driver.wait(until.elementLocated(By.css('[role=alert]')), 10_000);
    assert.match(await alert.getText(), /expired|invalid/i);
    await setPassword(second, NEW_PASSWORD);
    await logIn(inbox.address, NEW_PASSWORD);
    await driver.wait(until.urlContains('/dashboard'), 10_000);
  });

  it('answers the same for an address with no account', async function () {
    const member = new Inbox();
    await createAccount(member.address, OLD_PASSWORD);
    const forMember = await requestReset(member.address);
    const forStranger = await requestReset(new Inbox().address);
    assert.equal(forStranger, forMember);
  });

  it('builds the link from the real host, not a forwarded one', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    const res = await fetch(`${BASE_URL}/api/forgot-password`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Forwarded-Host': 'attacker.example' },
      body: JSON.stringify({ email: inbox.address }),
    });
    assert.ok(res.ok, `reset request returned ${res.status}`);
    assert.equal(new URL(resetLink(await inbox.next())).origin, new URL(BASE_URL).origin);
  });

  it('rejects an expired link', async function () {
    const ttl = Number(process.env.RESET_TTL_SECONDS);
    if (!ttl || ttl > 30) this.skip(); // needs a short reset-link lifetime in this environment

    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    const link = resetLink(await inbox.next());

    await new Promise((resolve) => setTimeout(resolve, (ttl + 1) * 1000)); // the server decides expiry
    await driver.get(link);
    const alert = await driver.wait(until.elementLocated(By.css('[role=alert]')), 10_000);
    assert.match(await alert.getText(), /expired/i);
  });
});

What each part does

  • The Inbox class provides a new email address for each test and keeps track of since, which is the time when it was created. next() makes a request to testmail.app to get the first email received after since and waits on the server-side for the email to arrive. It also advances since to make sure subsequent calls to next() will wait for new emails. This way we can use the same inbox to first get the password reset email and then the password changed email. Emails are listed starting from the most recent, hence .at(-1) to get the oldest new email.
  • The maximum time we wait for an email to arrive is 85 seconds to make sure we get a meaningful error message inside the suite’s two-minute Mocha timeout. The API call to fetch emails is live and will keep redirecting (307) to itself every 60 seconds and fetch will follow those redirects. So without a timeout it would just keep waiting for an email.
  • links() reads every href and decodes & to &, in the same way your email client would do before you click on the link. Otherwise a link like ?token=abc&id=7 would reach your app with a mangled query string.
  • createAccount() is a placeholder for you to replace with your own logic to create a user in your test environment.
  • We create a new browser instance for each test to make sure we don’t reuse cookies and login state between tests. --headless=new will start Chrome without opening a browser window (works both locally and in CI environments).
  • setPassword() waits for /login after submitting the form. Otherwise the next driver.get() call might happen before the previous form submission has completed and the “works only once” test will fail sporadically. We also make sure that the user is not logged in automatically after password reset as per OWASP’s recommendation.
  • logIn() clears cookies to make sure that we’re logged out before attempting to log in.

And the tests themselves:

  • sets a new password is the basic happy path. We also make sure that the user gets an email confirming that their password was changed and that this email doesn’t contain the new password.
  • sends one link, states the expiry, and no password makes sure that the password reset email follows the aforementioned recommendations. We use a Set to make sure there’s only one unique password reset link (in case you have both a button and a plain text copy of the same link). Don’t forget to change no-reply@example.com to your own “from” email address.
  • works only once makes sure that you get an error when you try to use an already used password reset link.
  • accepts only the newest link requests a password reset twice. The second call to next() will wait for the second email as since was already advanced after processing the first email. Then we make sure the first link no longer works and the second link does.
  • answers the same ensures that the response for a registered email address is the same as for an email address that doesn’t correspond to any user account. We don’t check that responses take the same amount of time. OWASP also recommends consistent response times. A dependable way to ensure that is to send the email asynchronously in a background job so both responses are equally fast.
  • builds the link from the real host sends a forged X-Forwarded-Host header to make sure the password reset link in the email still points to your application (the next section will explain why it’s important). Replace /api/forgot-password with the endpoint your forgot-password form posts to.
  • rejects an expired link runs only when RESET_TTL_SECONDS is 30 or less; otherwise Mocha marks it pending. Expired tokens are a bit trickier: unless you’ve made the token lifetime configurable (in which case, configure it to something short, as five seconds is plenty for the purposes of this test), or have a test-only endpoint for expiring tokens, your best bet may be to extract the bit of logic that checks whether a token has expired and write unit tests for it with a fake clock.

How a forged host header steals a reset token

Host header injection is a sneaky way of hijacking password reset flows. The email in this case will have been sent from your domain, will pass SPF and DKIM checks, and will look exactly as the user expects it to look. The only thing that’s amiss will be the link, which will point to the attacker’s domain.

host header injection in a password reset · why the suite checks the link's origin

host header injection in a password reset · why the suite checks the link's origin

It’s easy to fall foul of host header injection if you’re constructing absolute URLs in your application using the current host (in Express, req.hostname returns the X-Forwarded-Host value if you’ve turned on trust proxy; unless your proxy rewrites this header, an attacker will be able to set it). OWASP suggests always constructing these kinds of links using a URL from your application’s configuration, or validating the host header against a list of known values before using it. The suite’s host test keeps that fix from regressing.

Add the checks the suite leaves out

The tests for the remaining rows of the test-case table follow a similar pattern to those shown above. To test the Referrer-Policy header you can make a request to the URL in the email (shown below):

  it('serves the reset page with Referrer-Policy: no-referrer', async function () {
    const inbox = new Inbox();
    await createAccount(inbox.address, OLD_PASSWORD);
    await requestReset(inbox.address);
    const res = await fetch(resetLink(await inbox.next())); // a GET shouldn't use up the token
    assert.equal(res.headers.get('referrer-policy'), 'no-referrer');
  });

If you’re setting the policy with a <meta name="referrer"> tag you can assert against the page’s HTML. To test passwords that don’t match or are too weak, fill in the form (as setPassword() does) with invalid values and wait for the alert (rather than /login as in the happy path). To test tampered tokens, alter one of the characters in the token and expect the same alert as with used tokens. To test that other sessions are logged out, log in with a second webdriver instance before resetting the password, and check that the user has been logged out afterwards.

Run it in CI

If you’re using GitHub Actions, Ubuntu runner images come with Google Chrome preinstalled, so all you’ll need to install is Node and the two npm packages we discussed earlier (Chrome’s WebDriver will be downloaded for you by Selenium Manager).

# .github/workflows/password-reset.yml
name: password-reset-tests
on: [push, pull_request]

jobs:
  selenium:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: lts/*
          cache: npm
      - run: npm ci
      - run: npx mocha test/password-reset.test.mjs
        env:
          BASE_URL: https://staging.yourapp.com
          TESTMAIL_APIKEY: ${{ secrets.TESTMAIL_APIKEY }}
          TESTMAIL_NAMESPACE: ${{ vars.TESTMAIL_NAMESPACE }}
          RESET_TTL_SECONDS: ${{ vars.RESET_TTL_SECONDS }}

Store testmail.app’s API key as a GitHub Actions secret, but the email namespace and token lifetime can be stored as regular variables. If you don’t define RESET_TTL_SECONDS the related test will be skipped. Make sure that your staging environment is configured to send real emails to the inbox.testmail.app addresses made up by the tests. If your staging environment isn’t accessible from GitHub Actions’ infrastructure, you’ll either need to self-host GitHub Actions runners or spin up your application as part of the job. That said, the same npx mocha command should work in any CI system, provided Node and Chrome are available.

Troubleshooting

SymptomLikely causeFix
TimeoutError: The operation was aborted due to timeout from inbox.next()No email reached that address within 85 secondsCheck that the address is {namespace}.{tag}@inbox.testmail.app (an older version of this guide used user+tag@namespace.testmail.app, which never arrives), that createAccount() really created the user, and that the test environment sends email instead of logging it
next() throws testmail.app: ...The API answered with a failure, most often for a wrong key or namespaceCheck TESTMAIL_APIKEY and TESTMAIL_NAMESPACE; the message says what's wrong
no reset link in "..."Your reset path isn't /reset-passwordChange the path in resetLink() and in the "sends one link" test
The host test fails with your email provider's domainClick tracking rewrote the link to go through the provider's redirectTurn click tracking off for reset emails; the redirect also passes the token through a third party
The reset page rejects a link that works from a mail clientThe test opened the link with &amp; still in itUse links(), which decodes it
SessionNotCreatedError: session not created: This version of ChromeDriver only supports Chrome version 147An old chromedriver on your PATH, often from the chromedriver npm package (requiring it adds its binary to PATH) or a system installRemove it, or set SE_SKIP_DRIVER_IN_PATH=true so Selenium Manager downloads a matching driver
TimeoutError: Waiting for URL to contain "/login" after setting a passwordYour app goes somewhere else after a reset, or signs the user straight inWait for your own success state instead; if it signs users in automatically, consider OWASP's advice not to
"works only once" or "accepts only the newest link" times out waiting for [role=alert]The old link still opens the password form, so tokens aren't being invalidated, or your error message has no role="alert"Invalidate a token when it's used and when a newer one is issued; otherwise update the selector
Mocha reports Timeout of 120000ms exceededThe email wait and the browser steps took more than two minutesRaise this.timeout(), or find out why the email is slow

FAQ

How do you test password reset functionality?

Once you’ve tested the happy path end-to-end (request reset, receive email, follow link, set new password, log in with new password, old password no longer works), there are a number of edge cases worth covering: already-used links, outdated links, expired links, email addresses with no associated account, host header injection, rate limiting. We’d recommend automating the first batch of scenarios with a browser-based testing tool (such as Selenium), and checking headers and rate limits with raw HTTP requests.

Can Selenium read emails?

No. Selenium is a browser automation tool, so you’ll need some way of receiving emails in order to test password reset functionality: either an email testing API (such as testmail.app), a test SMTP server (which you configure your application to send emails to during testing), or IMAP credentials for a real email account. You could technically use Selenium to automate interactions with a web-based email client (such as Gmail), but this approach will be slower, more brittle, and likely to trip up anti-abuse protections.

Once you’ve retrieved the email (using testmail.app’s API in this article), parse out all href attributes from the email’s HTML body (remembering to convert &amp; to &), and select the one you expect to be the password reset link (based on its path). This is what the links() and resetLink() functions shown above are doing.

Make the reset link’s time-to-live configurable, and configure it to be only a few seconds long in your testing environment (this is what RESET_TTL_SECONDS is being used for in the code above), provide an endpoint for expiring tokens that’s only available in your testing environment, or factor out the bit of code that checks whether a token has expired into its own function and write unit tests for it using a mocked clock.

Should users be logged in automatically after a password reset?

OWASP doesn’t recommend this, so direct users to your login page instead, so that they log in using their new password. Automatically logging users in complicates your authentication and session management logic, increasing the surface area for potential vulnerabilities.

What are the negative test cases for forgot password?

An address not found, a confirmation that does not match, a password that does not match policy, a reused link, an expired link, a forged host header, too many requests for one account or IP address, and a less recent link after a more recent link. The table at the top lists the expected result for each.

Does the suite work with Firefox?

Yes. Selenium Manager will download geckodriver when the driver is built using forBrowser('firefox') and firefox.Options (from selenium-webdriver/firefox.js) just as it does chromedriver. Pass --headless to run headless.

Try it: create a (free) testmail.app account, export the namespace and API key and run npx mocha test/password-reset.test.mjs.

Subscribe to blog

Stay updated with our latest insights and curated articles delivered straight to your inbox.