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 { useSessionStore } from '@/stores/session' import VerifyView from '../VerifyView.vue' function mockResponse(status: number, body: unknown = null, headers: Record = {}) { 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 Response | Promise>) { 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 toastAdd: ReturnType vi.mock('@nuxt/ui/composables', () => ({ useToast: () => ({ add: toastAdd }), })) let currentWrapper: Awaited> | null = null async function mountVerify( path: string, handlers: Record Response | Promise> = {}, beforeMount: () => void = () => {}, ) { setActivePinia(createPinia()) toastAdd = vi.fn() const fetchMock = fetchRouter(handlers) global.fetch = fetchMock as unknown as typeof fetch await router.push(path) beforeMount() const wrapper = mount(VerifyView, { attachTo: document.body, global: { plugins: [router, uiPlugin], }, }) currentWrapper = wrapper await flushPromises() return { wrapper, fetchMock } } function findButton(wrapper: Awaited>, label: string) { return wrapper.findAll('button').find((button) => button.text() === label) } afterEach(async () => { currentWrapper?.unmount() currentWrapper = null vi.useRealTimers() await router.push('/login') }) describe('Verifying — the code submits automatically on load', () => { it('shows the full-card spinner and calls verify once with the code', async () => { const verify = vi.fn(() => new Promise(() => {})) const { wrapper, fetchMock } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': verify, }) expect(wrapper.find('[role="status"]').text()).toContain('Verifying your account…') expect(verify).toHaveBeenCalledTimes(1) expect(fetchMock).toHaveBeenCalledWith( '/v1/auth/verify', expect.objectContaining({ method: 'POST', body: JSON.stringify({ code: 'abc123' }), }), ) }) }) describe('Success — 200 refreshes the session and navigates to /home with a toast', () => { it('shows the success panel, then navigates after 800ms once session.retry resolves', async () => { const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(200), 'GET /v1/auth/me': () => mockResponse(200, { is_verified: true }), }) expect(wrapper.text()).toContain('Your account is verified') expect(wrapper.text()).toContain('Taking you to your dashboard…') expect(router.currentRoute.value.path).toBe('/register/validate') expect(toastAdd).toHaveBeenCalledWith({ color: 'success', icon: 'i-lucide-circle-check', title: 'Your account is verified', description: 'Welcome to RenewCMS.', }) await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/home'), { timeout: 2000, }) expect(toastAdd).toHaveBeenCalledTimes(1) const session = useSessionStore() expect(session.session).toMatchObject({ verified: true, displayName: '' }) }) }) describe('Invalid or expired — 403 offers a way to start over', () => { it('shows the error panel with the note and both actions', async () => { const pushSpy = vi.spyOn(router, 'push') const { wrapper } = await mountVerify( '/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(403) }, () => { const session = useSessionStore() session.session = { verified: false } session.status = 'ready' }, ) expect(wrapper.text()).toContain("This verification link doesn't work") expect(wrapper.text()).toContain( 'It may have expired (links last 2 hours) or already been used.', ) expect(wrapper.text()).toContain( 'Cancel your registration and start over to get a new link.', ) expect(findButton(wrapper, 'Cancel registration and start over')).toBeTruthy() expect(findButton(wrapper, 'Log out')).toBeTruthy() expect(router.currentRoute.value.path).toBe('/register/validate') expect(pushSpy).not.toHaveBeenCalledWith('/register/pending') pushSpy.mockRestore() }) }) describe('Cancel registration and start over — success', () => { it('sends DELETE with onForbidden passthrough, navigates to /register and toasts', async () => { const deleteRegister = vi.fn(() => mockResponse(200)) const { wrapper, fetchMock } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(403), 'DELETE /v1/auth/register': deleteRegister, }) await findButton(wrapper, 'Cancel registration and start over')?.trigger('click') await flushPromises() expect(fetchMock).toHaveBeenCalledWith( '/v1/auth/register', expect.objectContaining({ method: 'DELETE' }), ) await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/register')) expect(toastAdd).toHaveBeenCalledWith({ color: 'success', icon: 'i-lucide-circle-check', title: 'Registration cancelled', description: 'You can create the owner account again.', }) }) }) describe('Cancel registration and start over — failure shows an alert, not a redirect', () => { it.each([ { name: 'a 403 (already verified elsewhere)', handler: () => mockResponse(403), }, { name: 'a 500 response', handler: () => mockResponse(500) }, { name: 'a network failure', handler: () => Promise.reject(new TypeError('Failed to fetch')), }, ])('shows the failure alert and keeps the panel for $name', async ({ handler }) => { const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(403), 'DELETE /v1/auth/register': handler, }) await findButton(wrapper, 'Cancel registration and start over')?.trigger('click') await flushPromises() expect(wrapper.text()).toContain("Couldn't cancel registration") expect(wrapper.text()).toContain( 'Something went wrong on the server. Try again in a moment.', ) expect(wrapper.text()).toContain("This verification link doesn't work") expect(findButton(wrapper, 'Cancel registration and start over')).toBeTruthy() expect(findButton(wrapper, 'Log out')).toBeTruthy() expect(router.currentRoute.value.path).toBe('/register/validate') expect(toastAdd).not.toHaveBeenCalled() }) }) describe('Log out from the Invalid-or-expired state', () => { it('clears the session and navigates to /login', async () => { const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(403), 'POST /v1/auth/logout': () => mockResponse(200), }) const session = useSessionStore() session.session = { verified: false } session.status = 'ready' await findButton(wrapper, 'Log out')?.trigger('click') await flushPromises() expect(session.session).toBeNull() await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login')) }) }) describe('No session — the inline log-in form replaces the spinner', () => { it('shows the log-in form with the right copy and no forgot-password or footer', async () => { const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(401), }) expect(wrapper.find('h1').text()).toBe('Log in to finish verifying') expect(wrapper.text()).toContain( "You opened this link somewhere you're not logged in. Log in here and we'll verify your account right after.", ) expect(wrapper.find('input[placeholder="Your username"]').exists()).toBe(true) expect(wrapper.find('input[autocomplete="current-password"]').exists()).toBe(true) expect(wrapper.find('button[type="submit"]').text()).toBe('Log in and verify') expect(wrapper.text()).not.toContain('Forgot password?') expect(wrapper.text()).not.toContain('First time here?') expect(router.currentRoute.value.path).toBe('/register/validate') }) }) describe('No session — empty fields are caught on submit, as on Log in', () => { it('keeps the submit button enabled and shows both field errors without calling login', async () => { const login = vi.fn(() => mockResponse(200)) const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(401), 'POST /v1/auth/login': login, }) const submit = wrapper.find('button[type="submit"]') expect((submit.element as HTMLButtonElement).disabled).toBe(false) await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain('Use at least 3 characters.') expect(wrapper.text()).toContain('Enter your password.') expect(login).not.toHaveBeenCalled() }) }) describe('No session — successful login retries verification with the same code', () => { it('shows the spinner again and resends verify with the same code and passthrough options', async () => { const verify = vi.fn() verify.mockResolvedValueOnce(mockResponse(401)) verify.mockImplementationOnce(() => new Promise(() => {})) const { wrapper, fetchMock } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': verify, 'POST /v1/auth/login': () => mockResponse(200), }) await wrapper.find('input[placeholder="Your username"]').setValue('marta') await wrapper.find('input[autocomplete="current-password"]').setValue('limewash2026') await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.find('[role="status"]').text()).toContain('Verifying your account…') expect(fetchMock).toHaveBeenCalledWith( '/v1/auth/verify', expect.objectContaining({ method: 'POST', body: JSON.stringify({ code: 'abc123' }), }), ) expect(verify).toHaveBeenCalledTimes(2) }) }) describe('No session — wrong credentials during the inline login', () => { it('shows the mismatch alert, clears and refocuses the password, and never retries verify', async () => { const verify = vi.fn(() => mockResponse(401)) const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': verify, 'POST /v1/auth/login': () => mockResponse(403), }) await wrapper.find('input[placeholder="Your username"]').setValue('marta') await wrapper.find('input[autocomplete="current-password"]').setValue('wrong-password') await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain("That username and password don't match") expect(wrapper.text()).toContain('Check both and try again. Passwords are case-sensitive.') const passwordInput = wrapper.find('input[autocomplete="current-password"]') expect((passwordInput.element as HTMLInputElement).value).toBe('') expect(passwordInput.element).toBe(document.activeElement) expect(verify).toHaveBeenCalledTimes(1) }) }) describe('No session — too many login attempts', () => { it('shows the info alert with a live countdown on the submit button', async () => { vi.useFakeTimers() const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(401), 'POST /v1/auth/login': () => mockResponse(429, null, { 'Retry-After': '30' }), }) await wrapper.find('input[placeholder="Your username"]').setValue('marta') await wrapper.find('input[autocomplete="current-password"]').setValue('limewash2026') await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain('Too many attempts') expect(wrapper.text()).toContain('For your security, wait a moment before trying again.') const button = wrapper.find('button[type="submit"]') expect(button.text()).toBe('Try again in 0:30') expect((button.element as HTMLButtonElement).disabled).toBe(true) await vi.advanceTimersByTimeAsync(30000) await flushPromises() expect(wrapper.find('button[type="submit"]').text()).toBe('Log in and verify') }) }) describe('No session — server or network error during the inline login', () => { it.each([ { name: 'a 500 response', handler: () => mockResponse(500) }, { name: 'a network failure', handler: () => Promise.reject(new TypeError('Failed to fetch')), }, ])('shows the network/server alert and keeps the fields for $name', async ({ handler }) => { const { wrapper } = await mountVerify('/register/validate?c=abc123', { 'POST /v1/auth/verify': () => mockResponse(401), 'POST /v1/auth/login': handler, }) await wrapper.find('input[placeholder="Your username"]').setValue('marta') await wrapper.find('input[autocomplete="current-password"]').setValue('limewash2026') await wrapper.find('form').trigger('submit') await flushPromises() expect(wrapper.text()).toContain("Couldn't reach RenewCMS") expect(wrapper.text()).toContain('Check your connection and try again.') expect( (wrapper.find('input[placeholder="Your username"]').element as HTMLInputElement).value, ).toBe('marta') expect( (wrapper.find('input[autocomplete="current-password"]').element as HTMLInputElement) .value, ).toBe('limewash2026') expect( (wrapper.find('input[placeholder="Your username"]').element as HTMLInputElement) .disabled, ).toBe(false) }) }) describe('Missing code — no request is made', () => { it('renders the incomplete-link panel and navigates to /login', async () => { const { wrapper, fetchMock } = await mountVerify('/register/validate') expect(fetchMock).not.toHaveBeenCalled() expect(wrapper.text()).toContain('This link is incomplete') expect(wrapper.text()).toContain( 'The verification code is missing. Open the link from your email again, or copy the full address into your browser.', ) const action = findButton(wrapper, 'Go to log in') expect(action).toBeTruthy() await action?.trigger('click') await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login')) }) })