# Guide: Testing Password Resets

Automate the full password reset flow: trigger the email, wait for it, extract the reset link, and verify the reset completes successfully.

## Overview

Password reset testing follows this pattern:

1. Create a fresh address with `inboxes.create()` and an account for it.
2. Trigger your application's "forgot password" flow using that address.
3. Wait for the reset email with `waitFor()`, filtered by subject so the sign-up emails don't match.
4. Pick the reset link out of the email's extracted links.
5. Visit the reset link and complete the password change.
6. Assert the reset was successful.

## TypeScript Example

```typescript
import { ReceiverClient } from "@receiverdotemail/sdk";

const receiver = new ReceiverClient(); // reads RECEIVER_API_KEY
const APP = "https://your-app.com";
const post = (path: string, body: object) =>
  fetch(APP + path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });

describe("Password Reset", () => {
  it("sends a reset email and allows password change", async () => {
    // 1. A fresh address, with an account behind it
    const inbox = await receiver.inboxes.create({ prefix: "reset" });
    await post("/api/signup", { email: inbox.address, password: "oldPassword123!" });

    // 2. Trigger password reset in your app
    await post("/api/forgot-password", { email: inbox.address });

    // 3. Wait for the reset email (throws ReceiverTimeoutError after 30 s)
    const email = await receiver.emails.waitFor({
      recipient: inbox.address,
      since: inbox.createdAt,
      subject: "reset", // case-insensitive; skips the sign-up emails
      timeout: 30,
    });

    // 4. Pick the reset link: clean each URL, then match on the path
    const resetLink = email.links
      .map((link) => link.replace(/&amp;/g, "&").replace(/[.,;:!?)]+$/, ""))
      .find((link) => new URL(link).pathname.startsWith("/reset-password"));
    expect(resetLink).toBeDefined();

    // 5. Complete the reset (visit the link with new password)
    const response = await fetch(resetLink!, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ password: "newSecurePassword123!" }),
    });
    expect(response.ok).toBe(true);

    // 6. Verify login with new password works
    const loginResponse = await post("/api/login", {
      email: inbox.address,
      password: "newSecurePassword123!",
    });
    expect(loginResponse.ok).toBe(true);
  });
});
```

## Python Example

```python
import html
import re
from urllib.parse import urlsplit

import httpx
import pytest
import pytest_asyncio
from receiverdotemail import ReceiverClient

APP = "https://your-app.com"

@pytest_asyncio.fixture
async def receiver():
    async with ReceiverClient() as client:  # reads RECEIVER_API_KEY
        yield client

def find_link(links, path):
    """The first link to path, without the &amp; and trailing punctuation emails add."""
    for raw in links:
        link = re.sub(r"[.,;:!?)]+$", "", html.unescape(raw))
        if urlsplit(link).path.startswith(path):
            return link
    raise AssertionError(f"no {path} link in {links}")

@pytest.mark.asyncio
async def test_password_reset_flow(receiver):
    async with httpx.AsyncClient(base_url=APP) as http:
        # 1. A fresh address, with an account behind it
        inbox = await receiver.inboxes.create(prefix="reset")
        await http.post("/api/signup", json={"email": inbox.address, "password": "oldPassword123!"})

        # 2. Trigger password reset
        await http.post("/api/forgot-password", json={"email": inbox.address})

        # 3. Wait for the reset email (raises ReceiverTimeoutError after 30 s)
        email = await receiver.emails.wait_for(
            recipient=inbox.address,
            since=inbox.created_at,
            subject="reset",  # case-insensitive; skips the sign-up emails
            timeout=30,
        )

        # 4. Pick the reset link
        reset_link = find_link(email.links, "/reset-password")

        # 5. Complete the reset
        response = await http.post(reset_link, json={"password": "newSecurePassword123!"})
        assert response.status_code == 200

        # 6. Verify login with new password works
        login = await http.post(
            "/api/login",
            json={"email": inbox.address, "password": "newSecurePassword123!"},
        )
        assert login.status_code == 200
```

## Tips

- **Unique addresses**: `inboxes.create()` appends six random characters to the prefix, so parallel tests never share an address.
- **Link filtering**: Reset emails often contain multiple links (unsubscribe, privacy policy, etc.), and the same link can appear twice. Clean each link and match on its path, as the examples do; [Testing Magic-Link Login](https://www.receiver.email/docs/guides/magic-links) explains why.
- **Timeout**: `waitFor` throws `ReceiverTimeoutError` when nothing arrives within `timeout` (30 seconds by default), which fails the test with the `since` it waited from. It never returns `null`.
- **Test framework timeout**: Make sure your test framework's timeout is higher than the `waitFor` timeout (e.g. Jest default is 5s, so increase it).

## Next Steps

- [Testing OTP / 2FA](https://www.receiver.email/docs/guides/otp-verification)
- [Testing Magic Link Login](https://www.receiver.email/docs/guides/magic-links): choosing the right link
- [CI/CD Integration](https://www.receiver.email/docs/guides/ci-cd)
- [Testing Sign-Up Verification](https://www.receiver.email/docs/guides/email-verification): the confirm-your-address email, by link or by code

---

Source: https://www.receiver.email/docs/guides/password-reset
