feat: password reset full design and flow

This commit is contained in:
fsylvain committed 2026-09-28 05:06:16 +02:00
1 parent 938263cd6a
commit cb05b38f36
9 files changed
+1471 -4

No files matched your search

+263 -2
View File
@@ -1,9 +1,270 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import AuthShell from '@/components/AuthShell.vue'
import PasswordStrengthHint from '@/components/PasswordStrengthHint.vue'
import ResultPanel from '@/components/ResultPanel.vue'
import { ApiError, useApi } from '@/composables/useApi'
const route = useRoute()
const router = useRouter()
const api = useApi()
const code = typeof route.query.c === 'string' ? route.query.c : ''
const email = typeof route.query.email === 'string' ? route.query.email : ''
const missingParameters = !code || !email
const password = ref('')
const confirmPassword = ref('')
const passwordShown = ref(false)
const confirmPasswordShown = ref(false)
const submitting = ref(false)
const submitFailed = ref(false)
const mismatchTouched = ref(false)
const serverErrorAlert = ref(false)
const expired = ref(false)
const passwordValid = computed(() => password.value.length >= 8)
const passwordsMatch = computed(() => confirmPassword.value === password.value)
const showLengthError = computed(() => submitFailed.value && !passwordValid.value)
const showMatchError = computed(() => mismatchTouched.value && !passwordsMatch.value)
const passwordRules = computed(() => [{ label: 'At least 8 characters', met: passwordValid.value }])
const confirmPasswordRules = computed(() => [
{ label: 'Passwords match', met: passwordsMatch.value },
])
const confirmError = computed(() => (showMatchError.value ? "The passwords don't match." : ''))
function goToRequest() {
router.push('/register/reset/request')
}
function goToLogin() {
router.push('/login')
}
const expiredActions = [
{ label: 'Request a new link', onClick: goToRequest },
{
label: 'Back to log in',
color: 'neutral' as const,
variant: 'outline' as const,
onClick: goToLogin,
},
]
const missingParametersActions = [{ label: 'Request a new link', onClick: goToRequest }]
const confirmDescription =
"Pick something you haven't used here before. You'll log in with it next."
async function onSubmit() {
if (submitting.value) {
return
}
mismatchTouched.value = true
if (!passwordValid.value || !passwordsMatch.value) {
submitFailed.value = true
return
}
serverErrorAlert.value = false
submitting.value = true
try {
await api.request('/v1/auth/password-reset/confirm', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email,
code,
password: password.value,
}),
})
await router.push('/login?reason=password-changed')
} catch (error) {
if (error instanceof ApiError && error.status === 403) {
expired.value = true
return
}
serverErrorAlert.value = true
} finally {
submitting.value = false
}
}
</script>
<template>
<AuthShell title="Choose a new password">
<p>Reset confirm placeholder.</p>
<AuthShell
:title="expired || missingParameters ? '' : 'Choose a new password'"
:description="expired || missingParameters ? undefined : confirmDescription"
>
<template v-if="serverErrorAlert" #notice>
<UAlert
color="error"
icon="i-lucide-circle-x"
title="Couldn't reach RenewCMS"
description="Check your connection and try again."
variant="soft"
:close="false"
role="alert"
/>
</template>
<template v-if="missingParameters" #default>
<ResultPanel
tone="error"
icon="i-lucide-link-2-off"
title="This link is incomplete"
description="Part of the reset link is missing. Open it from your email again, or request a new one."
:actions="missingParametersActions"
/>
</template>
<template v-else-if="expired" #default>
<ResultPanel
tone="error"
icon="i-lucide-link-2-off"
title="This reset link has expired"
description="Reset links work once, for 1 hour. Request a new one and use it within the hour."
:actions="expiredActions"
/>
</template>
<template v-else #default="{ controlSize, controlClass, inputClass }">
<UForm
:state="{ email, password, confirmPassword }"
class="flex flex-col gap-4.5"
@submit="onSubmit"
>
<UFormField
label="Email"
name="email"
help="From your reset link."
:size="controlSize"
>
<UInput
:model-value="email"
placeholder="you@example.com"
readonly
variant="outline"
color="primary"
:size="controlSize"
:ui="{
base: `${inputClass} bg-elevated text-dimmed ring-(--ui-border)`,
}"
class="w-full"
/>
</UFormField>
<UFormField label="New password" name="password" :size="controlSize">
<template #help>
<PasswordStrengthHint
:rules="passwordRules"
:show-errors="showLengthError"
/>
</template>
<UInput
id="reset-new-password"
v-model="password"
:type="passwordShown ? 'text' : 'password'"
autocomplete="new-password"
:disabled="submitting"
variant="outline"
color="primary"
:size="controlSize"
:ui="{
base: `${inputClass} ${passwordShown ? '' : 'tracking-[2px]'}`,
trailing: 'pe-1',
}"
class="w-full"
>
<template #trailing>
<UButton
:icon="passwordShown ? 'i-lucide-eye-off' : 'i-lucide-eye'"
variant="ghost"
color="neutral"
size="sm"
square
class="size-8 justify-center text-toned"
:aria-label="passwordShown ? 'Hide password' : 'Show password'"
:aria-pressed="passwordShown"
@click="passwordShown = !passwordShown"
/>
</template>
</UInput>
</UFormField>
<UFormField label="Confirm new password" name="confirmPassword" :size="controlSize">
<template #help>
<span
v-if="confirmError"
role="alert"
class="mb-1.5 flex items-center gap-1.5 text-xs/[18px] text-error"
>
<UIcon
name="i-lucide-circle-alert"
class="size-3.5 shrink-0 text-error"
/>
{{ confirmError }}
</span>
<PasswordStrengthHint
:rules="confirmPasswordRules"
:show-errors="showMatchError"
/>
</template>
<UInput
id="reset-confirm-password"
v-model="confirmPassword"
:type="confirmPasswordShown ? 'text' : 'password'"
autocomplete="new-password"
:disabled="submitting"
variant="outline"
color="primary"
:highlight="!!confirmError"
:size="controlSize"
:ui="{
base: `${inputClass} ${confirmPasswordShown ? '' : 'tracking-[2px]'}`,
trailing: 'pe-1',
}"
class="w-full"
@blur="mismatchTouched = true"
>
<template #trailing>
<UButton
:icon="confirmPasswordShown ? 'i-lucide-eye-off' : 'i-lucide-eye'"
variant="ghost"
color="neutral"
size="sm"
square
class="size-8 justify-center text-toned"
:aria-label="
confirmPasswordShown ? 'Hide password' : 'Show password'
"
:aria-pressed="confirmPasswordShown"
@click="confirmPasswordShown = !confirmPasswordShown"
/>
</template>
</UInput>
</UFormField>
<UButton
type="submit"
block
:size="controlSize"
:ui="{ base: controlClass }"
:loading="submitting"
:disabled="submitting"
>
{{ submitting ? 'Changing password…' : 'Change password' }}
</UButton>
</UForm>
</template>
</AuthShell>
</template>
+192 -2
View File
@@ -1,9 +1,199 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import AuthShell from '@/components/AuthShell.vue'
import ResultPanel from '@/components/ResultPanel.vue'
import { ApiError, useApi } from '@/composables/useApi'
import { useRetryAfter } from '@/composables/useRetryAfter'
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
interface AlertState {
tone: 'error' | 'info'
icon: string
title: string
description: string
}
const tooManyAttemptsAlert: AlertState = {
tone: 'info',
icon: 'i-lucide-timer',
title: 'Too many requests',
description: 'Wait a moment before asking for another link.',
}
const serverErrorAlert: AlertState = {
tone: 'error',
icon: 'i-lucide-circle-x',
title: "Couldn't send the link",
description: 'Check your connection and try again.',
}
const router = useRouter()
const api = useApi()
const retryAfter = useRetryAfter()
const email = ref('')
const emailError = ref('')
const submitting = ref(false)
const sent = ref(false)
const alert = ref<AlertState | null>(null)
const alertRole = computed(() => (alert.value?.tone === 'error' ? 'alert' : 'status'))
const submitDisabled = computed(() => submitting.value || retryAfter.active.value)
const submitLabel = computed(() => {
if (submitting.value) {
return 'Sending…'
}
if (retryAfter.active.value) {
return `Try again in ${retryAfter.formatted.value}`
}
return 'Send reset link'
})
function validate() {
emailError.value = EMAIL_PATTERN.test(email.value)
? ''
: 'Enter a full email address, like name@example.com.'
return !emailError.value
}
function goToLogin() {
router.push('/login')
}
const resultPanelActions = [
{
label: 'Back to log in',
color: 'neutral' as const,
variant: 'outline' as const,
onClick: goToLogin,
},
]
function handleRequestError(error: unknown) {
if (error instanceof ApiError && error.status === 429) {
alert.value = tooManyAttemptsAlert
retryAfter.start(error.retryAfter ?? 0)
return
}
alert.value = serverErrorAlert
}
async function onSubmit() {
if (submitDisabled.value) {
return
}
if (!validate()) {
return
}
alert.value = null
submitting.value = true
try {
await api.request('/v1/auth/password-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email.value }),
})
sent.value = true
} catch (error) {
handleRequestError(error)
} finally {
submitting.value = false
}
}
const pageTitle = computed(() => (sent.value ? '' : 'Reset your password'))
const pageDescription = computed(() =>
sent.value
? undefined
: "Enter the email for your account and we'll send you a link to choose a new password.",
)
</script>
<template>
<AuthShell title="Reset your password">
<p>Reset request placeholder.</p>
<AuthShell :title="pageTitle" :description="pageDescription">
<template v-if="alert" #notice>
<UAlert
:color="alert.tone"
:icon="alert.icon"
:title="alert.title"
:description="alert.description"
variant="soft"
:close="false"
:role="alertRole"
/>
</template>
<template v-if="sent" #default>
<ResultPanel
tone="success"
icon="i-lucide-mail-check"
title="Check your email"
description="If an account exists for that email, a password reset link has been sent."
:actions="resultPanelActions"
>
<p class="text-sm text-muted">The link expires in 1 hour.</p>
</ResultPanel>
</template>
<template v-else #default="{ controlSize, controlClass, inputClass }">
<UForm :state="{ email }" class="flex flex-col gap-4.5" @submit="onSubmit">
<UFormField
label="Email"
name="email"
:error="emailError || undefined"
:size="controlSize"
>
<template v-if="emailError" #error="{ error }">
<span class="flex items-center gap-1.5">
<UIcon
name="i-lucide-circle-alert"
class="size-3.5 shrink-0 text-error"
/>
{{ error }}
</span>
</template>
<UInput
v-model="email"
type="email"
placeholder="you@example.com"
autocomplete="email"
:disabled="submitDisabled"
variant="outline"
color="primary"
:highlight="!!emailError"
:size="controlSize"
:ui="{ base: inputClass, trailing: 'pe-1' }"
class="w-full"
/>
</UFormField>
<UButton
type="submit"
block
:size="controlSize"
:ui="{ base: controlClass }"
:loading="submitting"
:disabled="submitDisabled"
>
{{ submitLabel }}
</UButton>
</UForm>
</template>
<template v-if="!sent" #footer>
<RouterLink
to="/login"
class="font-medium text-highlighted underline underline-offset-3"
>
Back to log in
</RouterLink>
</template>
</AuthShell>
</template>
@@ -0,0 +1,326 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import ResultPanel from '@/components/ResultPanel.vue'
import ResetConfirmView from '../ResetConfirmView.vue'
function mockResponse(status: number, body: unknown = null, headers: Record<string, string> = {}) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name: string) => headers[name] ?? null },
json: async () => body,
} as unknown as Response
}
function routeFor(url: string, init?: RequestInit) {
const method = init?.method ?? 'GET'
return `${method} ${url}`
}
function fetchRouter(handlers: Record<string, () => Response | Promise<Response>>) {
return vi.fn((url: string, init?: RequestInit) => {
const key = routeFor(url, init)
const handler = handlers[key]
if (!handler) {
throw new Error(`Unexpected fetch call: ${key}`)
}
return handler()
})
}
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
async function mountResetConfirm(
path: string,
handlers: Record<string, () => Response | Promise<Response>> = {},
) {
setActivePinia(createPinia())
const fetchMock = fetchRouter(handlers)
global.fetch = fetchMock as unknown as typeof fetch
await router.push(path)
const wrapper = mount(ResetConfirmView, {
attachTo: document.body,
global: {
plugins: [router, uiPlugin],
},
})
currentWrapper = wrapper
await flushPromises()
return { wrapper, fetchMock }
}
const DEFAULT_PATH = '/register/reset/validate?c=abc123&email=marta%40renew.example'
function newPasswordInput(wrapper: Awaited<ReturnType<typeof mountResetConfirm>>) {
return wrapper.find('#reset-new-password')
}
function confirmPasswordInput(wrapper: Awaited<ReturnType<typeof mountResetConfirm>>) {
return wrapper.find('#reset-confirm-password')
}
async function fillPasswords(
wrapper: Awaited<ReturnType<typeof mountResetConfirm>>,
password: string,
confirm: string,
) {
await newPasswordInput(wrapper).setValue(password)
await confirmPasswordInput(wrapper).setValue(confirm)
}
afterEach(async () => {
currentWrapper?.unmount()
currentWrapper = null
await router.push('/login')
})
describe('Default — both parameters present, an untouched form', () => {
it('renders the empty form', async () => {
const { wrapper } = await mountResetConfirm(DEFAULT_PATH)
expect(wrapper.find('h1').text()).toBe('Choose a new password')
expect(wrapper.text()).toContain(
"Pick something you haven't used here before. You'll log in with it next.",
)
const emailField = wrapper.find('input[placeholder="you@example.com"]')
expect((emailField.element as HTMLInputElement).value).toBe('marta@renew.example')
expect((emailField.element as HTMLInputElement).readOnly).toBe(true)
expect(wrapper.text()).toContain('From your reset link.')
expect((newPasswordInput(wrapper).element as HTMLInputElement).value).toBe('')
expect(wrapper.text()).toContain('At least 8 characters')
expect((confirmPasswordInput(wrapper).element as HTMLInputElement).value).toBe('')
expect(wrapper.text()).toContain('Passwords match')
expect(wrapper.find('button[type="submit"]').text()).toBe('Change password')
})
})
describe('Too short — fewer than 8 characters blocks submission', () => {
it('never calls the endpoint and marks the length rule as errored', async () => {
const confirm = vi.fn(() => mockResponse(200))
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': confirm,
})
await fillPasswords(wrapper, 'lime', 'lime')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(confirm).not.toHaveBeenCalled()
const items = wrapper.findAll('li')
const lengthItem = items.find((item) => item.text().includes('At least 8 characters'))
expect(lengthItem?.text()).toContain('not met')
const matchItem = items.find((item) => item.text().includes('Passwords match'))
expect(matchItem?.text()).toContain('met')
})
})
describe('Mismatch — caught on blur and on submit', () => {
it('shows the mismatch error and blocks the request', async () => {
const confirm = vi.fn(() => mockResponse(200))
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': confirm,
})
await newPasswordInput(wrapper).setValue('limewash2026')
await confirmPasswordInput(wrapper).setValue('limewash2025')
await confirmPasswordInput(wrapper).trigger('blur')
expect(wrapper.text()).toContain("The passwords don't match.")
const matchItemAfterBlur = wrapper
.findAll('li')
.find((item) => item.text().includes('Passwords match'))
expect(matchItemAfterBlur?.find('svg').classes()).toContain('text-error')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(confirm).not.toHaveBeenCalled()
expect(wrapper.text()).toContain("The passwords don't match.")
const matchItemAfterSubmit = wrapper
.findAll('li')
.find((item) => item.text().includes('Passwords match'))
expect(matchItemAfterSubmit?.find('svg').classes()).toContain('text-error')
})
})
describe('Submitting — fields and button are disabled while the request is in flight', () => {
it('disables the fields and shows the loading label', async () => {
let resolveConfirm: (() => void) | null = null
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': () =>
new Promise((resolve) => {
resolveConfirm = () => resolve(mockResponse(200))
}),
})
await fillPasswords(wrapper, 'limewash2026', 'limewash2026')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect((newPasswordInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
expect((confirmPasswordInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Changing password…')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(true)
resolveConfirm?.()
await flushPromises()
})
})
describe('Success — a 200 hands off to the log-in screen', () => {
it('navigates to /login?reason=password-changed', async () => {
const { wrapper, fetchMock } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': () => mockResponse(200),
})
await fillPasswords(wrapper, 'limewash2026', 'limewash2026')
await wrapper.find('form').trigger('submit')
await vi.waitFor(() =>
expect(router.currentRoute.value.fullPath).toBe('/login?reason=password-changed'),
)
expect(fetchMock).toHaveBeenCalledWith(
'/v1/auth/password-reset/confirm',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({
email: 'marta@renew.example',
code: 'abc123',
password: 'limewash2026',
}),
}),
)
})
})
describe('Invalid or expired — a 403 replaces the form with a ResultPanel', () => {
it('shows the panel and navigates depending on the action', async () => {
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': () => mockResponse(403),
})
await fillPasswords(wrapper, 'limewash2026', 'limewash2026')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(wrapper.find('form').exists()).toBe(false)
expect(wrapper.text()).toContain('This reset link has expired')
expect(wrapper.text()).toContain(
'Reset links work once, for 1 hour. Request a new one and use it within the hour.',
)
const resultPanel = wrapper.findComponent(ResultPanel)
expect(resultPanel.props('tone')).toBe('error')
expect(resultPanel.props('icon')).toBe('i-lucide-link-2-off')
const buttons = wrapper.findAll('button')
const requestNew = buttons.find((button) => button.text() === 'Request a new link')
expect(requestNew).toBeTruthy()
await requestNew?.trigger('click')
await vi.waitFor(() =>
expect(router.currentRoute.value.path).toBe('/register/reset/request'),
)
})
it('navigates to /login when Back to log in is activated', async () => {
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': () => mockResponse(403),
})
await fillPasswords(wrapper, 'limewash2026', 'limewash2026')
await wrapper.find('form').trigger('submit')
await flushPromises()
const buttons = wrapper.findAll('button')
const backToLogin = buttons.find((button) => button.text() === 'Back to log in')
expect(backToLogin).toBeTruthy()
await backToLogin?.trigger('click')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
})
})
describe('Server or network error — the form keeps its values and re-enables', () => {
it.each([
{ name: 'a 500 response', handler: () => mockResponse(500) },
{
name: 'a network failure',
handler: () => Promise.reject(new TypeError('Failed to fetch')),
},
])('shows the error alert and keeps the values for $name', async ({ handler }) => {
const confirm = vi.fn(handler)
const { wrapper } = await mountResetConfirm(DEFAULT_PATH, {
'POST /v1/auth/password-reset/confirm': confirm,
})
await fillPasswords(wrapper, 'limewash2026', 'limewash2026')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect(confirm).toHaveBeenCalled()
expect(wrapper.text()).toContain("Couldn't reach RenewCMS")
expect(wrapper.text()).toContain('Check your connection and try again.')
expect(wrapper.find('form').exists()).toBe(true)
expect((newPasswordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
expect((confirmPasswordInput(wrapper).element as HTMLInputElement).value).toBe(
'limewash2026',
)
expect((newPasswordInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
expect((confirmPasswordInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Change password')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
})
})
describe('Missing parameters — either missing parameter blocks the request', () => {
it.each([
{
path: '/register/reset/validate?email=marta%40renew.example',
},
{ path: '/register/reset/validate?c=abc123' },
{ path: '/register/reset/validate' },
])('renders the missing-parameters panel for $path', async ({ path }) => {
const confirm = vi.fn(() => mockResponse(200))
const { wrapper } = await mountResetConfirm(path, {
'POST /v1/auth/password-reset/confirm': confirm,
})
expect(confirm).not.toHaveBeenCalled()
expect(wrapper.find('form').exists()).toBe(false)
expect(wrapper.text()).toContain('This link is incomplete')
expect(wrapper.text()).toContain(
'Part of the reset link is missing. Open it from your email again, or request a new one.',
)
const resultPanel = wrapper.findComponent(ResultPanel)
expect(resultPanel.props('tone')).toBe('error')
expect(resultPanel.props('icon')).toBe('i-lucide-link-2-off')
expect(resultPanel.props('actions')).toHaveLength(1)
const action = wrapper.find('button')
expect(action.text()).toBe('Request a new link')
await action.trigger('click')
await vi.waitFor(() =>
expect(router.currentRoute.value.path).toBe('/register/reset/request'),
)
})
})
@@ -0,0 +1,222 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import uiPlugin from '@nuxt/ui/vue-plugin'
import router from '@/router'
import ResultPanel from '@/components/ResultPanel.vue'
import ResetRequestView from '../ResetRequestView.vue'
function mockResponse(status: number, body: unknown = null, headers: Record<string, string> = {}) {
return {
ok: status >= 200 && status < 300,
status,
headers: { get: (name: string) => headers[name] ?? null },
json: async () => body,
} as unknown as Response
}
function routeFor(url: string, init?: RequestInit) {
const method = init?.method ?? 'GET'
return `${method} ${url}`
}
function fetchRouter(handlers: Record<string, () => Response | Promise<Response>>) {
return vi.fn((url: string, init?: RequestInit) => {
const key = routeFor(url, init)
const handler = handlers[key]
if (!handler) {
throw new Error(`Unexpected fetch call: ${key}`)
}
return handler()
})
}
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
async function mountResetRequest(
handlers: Record<string, () => Response | Promise<Response>> = {},
) {
setActivePinia(createPinia())
const fetchMock = fetchRouter(handlers)
global.fetch = fetchMock as unknown as typeof fetch
await router.push('/register/reset/request')
const wrapper = mount(ResetRequestView, {
attachTo: document.body,
global: {
plugins: [router, uiPlugin],
},
})
currentWrapper = wrapper
await flushPromises()
return { wrapper, fetchMock }
}
function emailInput(wrapper: Awaited<ReturnType<typeof mountResetRequest>>) {
return wrapper.find('input[placeholder="you@example.com"]')
}
async function fillAndSubmit(
wrapper: Awaited<ReturnType<typeof mountResetRequest>>,
email: string,
) {
await emailInput(wrapper).setValue(email)
await wrapper.find('form').trigger('submit')
await flushPromises()
}
afterEach(async () => {
currentWrapper?.unmount()
currentWrapper = null
await router.push('/login')
})
describe('Default — a fresh, empty form', () => {
it('renders the empty state', async () => {
const { wrapper } = await mountResetRequest()
expect(wrapper.find('h1').text()).toBe('Reset your password')
expect(wrapper.text()).toContain(
"Enter the email for your account and we'll send you a link to choose a new password.",
)
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('')
expect(wrapper.find('button[type="submit"]').text()).toBe('Send reset link')
const footerLink = wrapper.find('a[href="/login"]')
expect(footerLink.exists()).toBe(true)
expect(footerLink.text()).toBe('Back to log in')
})
})
describe('Validation error — an invalid email blocks the request', () => {
it('never calls the endpoint and shows the field error', async () => {
const request = vi.fn(() => mockResponse(200))
const { wrapper } = await mountResetRequest({
'POST /v1/auth/password-reset': request,
})
await fillAndSubmit(wrapper, 'marta@renew')
expect(request).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('Enter a full email address, like name@example.com.')
})
})
describe('Submitting — the field and button are disabled while the request is in flight', () => {
it('disables the field and shows the loading label', async () => {
let resolveRequest: (() => void) | null = null
const { wrapper } = await mountResetRequest({
'POST /v1/auth/password-reset': () =>
new Promise((resolve) => {
resolveRequest = () => resolve(mockResponse(200))
}),
})
await emailInput(wrapper).setValue('marta@renew.example')
await wrapper.find('form').trigger('submit')
await flushPromises()
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Sending…')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(true)
resolveRequest?.()
await flushPromises()
})
})
describe('Sent — any 200 shows the same neutral confirmation', () => {
it('replaces the form with a ResultPanel and navigates back to log in', async () => {
const { wrapper, fetchMock } = await mountResetRequest({
'POST /v1/auth/password-reset': () => mockResponse(200),
})
await fillAndSubmit(wrapper, 'marta@renew.example')
expect(fetchMock).toHaveBeenCalledWith(
'/v1/auth/password-reset',
expect.objectContaining({
method: 'POST',
body: JSON.stringify({ email: 'marta@renew.example' }),
}),
)
expect(wrapper.find('form').exists()).toBe(false)
expect(wrapper.text()).toContain('Check your email')
expect(wrapper.text()).toContain(
'If an account exists for that email, a password reset link has been sent.',
)
expect(wrapper.text()).toContain('The link expires in 1 hour.')
const resultPanel = wrapper.findComponent(ResultPanel)
expect(resultPanel.props('tone')).toBe('success')
expect(resultPanel.props('icon')).toBe('i-lucide-mail-check')
const action = wrapper.find('button')
expect(action.text()).toBe('Back to log in')
await action.trigger('click')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
})
})
describe('Too many attempts — the button is disabled with a live countdown', () => {
it('counts down from the Retry-After value and re-enables at zero', async () => {
vi.useFakeTimers()
const { wrapper } = await mountResetRequest({
'POST /v1/auth/password-reset': () => mockResponse(429, null, { 'Retry-After': '58' }),
})
await fillAndSubmit(wrapper, 'marta@renew.example')
expect(wrapper.text()).toContain('Too many requests')
expect(wrapper.text()).toContain('Wait a moment before asking for another link.')
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('marta@renew.example')
const button = wrapper.find('button[type="submit"]')
expect(button.text()).toBe('Try again in 0:58')
expect((button.element as HTMLButtonElement).disabled).toBe(true)
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
await vi.advanceTimersByTimeAsync(58000)
await flushPromises()
expect(wrapper.find('button[type="submit"]').text()).toBe('Send reset link')
expect((wrapper.find('button[type="submit"]').element as HTMLButtonElement).disabled).toBe(
false,
)
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
vi.useRealTimers()
})
})
describe('Server or network error — the field keeps its value and re-enables', () => {
it.each([
{ name: 'a 500 response', handler: () => mockResponse(500) },
{
name: 'a network failure',
handler: () => Promise.reject(new TypeError('Failed to fetch')),
},
])('shows the error alert and keeps the value for $name', async ({ handler }) => {
const request = vi.fn(handler)
const { wrapper } = await mountResetRequest({
'POST /v1/auth/password-reset': request,
})
await fillAndSubmit(wrapper, 'marta@renew.example')
expect(request).toHaveBeenCalled()
expect(wrapper.text()).toContain("Couldn't send the link")
expect(wrapper.text()).toContain('Check your connection and try again.')
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('marta@renew.example')
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
const submitButton = wrapper.find('button[type="submit"]')
expect(submitButton.text()).toBe('Send reset link')
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
})
})