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

@@ -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)
})
})