feat: register T1 (pending, verify)
This commit is contained in:
1 parent
3c3f7c6194
commit
4e41d60142
29 files changed
+2162
-42
No files matched your search
@@ -0,0 +1,299 @@
|
||||
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 PendingView from '../PendingView.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()
|
||||
})
|
||||
}
|
||||
|
||||
function createOverlayMock() {
|
||||
let props: Record<string, unknown> | null = null
|
||||
let resolveOpen: ((value: unknown) => void) | null = null
|
||||
const create = vi.fn((_component: unknown, options: { props: Record<string, unknown> }) => {
|
||||
props = options.props
|
||||
return {
|
||||
open: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveOpen = resolve
|
||||
}),
|
||||
}
|
||||
})
|
||||
return {
|
||||
create,
|
||||
getProps: () => props,
|
||||
resolveOpen: (value: unknown) => resolveOpen?.(value),
|
||||
}
|
||||
}
|
||||
|
||||
let overlayMock: ReturnType<typeof createOverlayMock>
|
||||
let toastAdd: ReturnType<typeof vi.fn>
|
||||
|
||||
vi.mock('@nuxt/ui/composables', () => ({
|
||||
useOverlay: () => overlayMock,
|
||||
useToast: () => ({ add: toastAdd }),
|
||||
}))
|
||||
|
||||
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
|
||||
|
||||
async function mountPending(
|
||||
handlers: Record<string, () => Response | Promise<Response>> = {},
|
||||
pendingEmail: string | null = 'marta@renew.example',
|
||||
) {
|
||||
setActivePinia(createPinia())
|
||||
overlayMock = createOverlayMock()
|
||||
toastAdd = vi.fn()
|
||||
const fetchMock = fetchRouter(handlers)
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
if (pendingEmail === null) {
|
||||
sessionStorage.removeItem('renewcms:pendingEmail')
|
||||
} else {
|
||||
sessionStorage.setItem('renewcms:pendingEmail', pendingEmail)
|
||||
}
|
||||
await router.push('/register/pending')
|
||||
const wrapper = mount(PendingView, {
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
plugins: [router, uiPlugin],
|
||||
},
|
||||
})
|
||||
currentWrapper = wrapper
|
||||
await flushPromises()
|
||||
return { wrapper, fetchMock }
|
||||
}
|
||||
|
||||
function findButton(wrapper: Awaited<ReturnType<typeof mount>>, label: string) {
|
||||
return wrapper.findAll('button').find((button) => button.text() === label)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
currentWrapper?.unmount()
|
||||
currentWrapper = null
|
||||
sessionStorage.removeItem('renewcms:pendingEmail')
|
||||
await router.push('/login')
|
||||
})
|
||||
|
||||
describe('Default — the email is known from a just-completed registration', () => {
|
||||
it('shows the ResultPanel with the interpolated email', async () => {
|
||||
const { wrapper } = await mountPending({}, 'marta@renew.example')
|
||||
|
||||
expect(wrapper.text()).toContain('Check your email')
|
||||
expect(wrapper.text()).toContain(
|
||||
'We sent a verification link to marta@renew.example. It expires in 2 hours.',
|
||||
)
|
||||
expect(wrapper.text()).toContain(
|
||||
"Opened it on another device? That works too; you'll log in there first. Can't find it? Check your spam folder. If the link has expired, cancel your registration and start again.",
|
||||
)
|
||||
expect(findButton(wrapper, 'Log out')).toBeTruthy()
|
||||
expect(findButton(wrapper, 'Cancel registration')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Email unknown — arrived by logging in as an unverified account', () => {
|
||||
it('shows the generic text with no email', async () => {
|
||||
const { wrapper } = await mountPending({}, null)
|
||||
|
||||
expect(wrapper.text()).toContain('Check your email')
|
||||
expect(wrapper.text()).toContain(
|
||||
'We sent a verification link to the email you registered with. It expires in 2 hours.',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Logging out', () => {
|
||||
it('disables both actions while in flight, clears the session and navigates to /login', async () => {
|
||||
let resolveLogout: (() => void) | null = null
|
||||
const { wrapper } = await mountPending({
|
||||
'POST /v1/auth/logout': () =>
|
||||
new Promise((resolve) => {
|
||||
resolveLogout = () => resolve(mockResponse(200))
|
||||
}),
|
||||
})
|
||||
const session = useSessionStore()
|
||||
session.session = { verified: false }
|
||||
session.status = 'ready'
|
||||
|
||||
await findButton(wrapper, 'Log out')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect((findButton(wrapper, 'Log out')?.element as HTMLButtonElement).disabled).toBe(true)
|
||||
expect(
|
||||
(findButton(wrapper, 'Cancel registration')?.element as HTMLButtonElement).disabled,
|
||||
).toBe(true)
|
||||
|
||||
resolveLogout?.()
|
||||
await flushPromises()
|
||||
|
||||
expect(session.session).toBeNull()
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('Confirm cancel — the destructive dialog opens', () => {
|
||||
it('opens ConfirmDialog with the expected props, leaving the ResultPanel shown', async () => {
|
||||
const { wrapper } = await mountPending()
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(overlayMock.create).toHaveBeenCalledTimes(1)
|
||||
const props = overlayMock.getProps() as Record<string, unknown>
|
||||
expect(props.title).toBe('Cancel your registration?')
|
||||
expect(props.description).toBe(
|
||||
'Your account will be deleted. You can register again with the same or a different email.',
|
||||
)
|
||||
expect(props.confirmLabel).toBe('Cancel registration')
|
||||
expect(props.cancelLabel).toBe('Keep my account')
|
||||
expect(props.pendingLabel).toBe('Cancelling…')
|
||||
expect(props.tone).toBe('danger')
|
||||
expect(typeof props.action).toBe('function')
|
||||
|
||||
expect(wrapper.text()).toContain('Check your email')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancelling — the DELETE is in flight and the dialog can not be dismissed', () => {
|
||||
it('sends DELETE /v1/auth/register from the dialog action', async () => {
|
||||
const deleteRegister = vi.fn(() => mockResponse(200))
|
||||
const { wrapper, fetchMock } = await mountPending({
|
||||
'DELETE /v1/auth/register': deleteRegister,
|
||||
})
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const props = overlayMock.getProps() as { action: () => Promise<void> }
|
||||
await props.action()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/auth/register',
|
||||
expect.objectContaining({ method: 'DELETE' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Keep my account — the dialog is dismissed without deleting anything', () => {
|
||||
it('never calls DELETE and keeps the ResultPanel unchanged', async () => {
|
||||
const deleteRegister = vi.fn(() => mockResponse(200))
|
||||
const { wrapper } = await mountPending({
|
||||
'DELETE /v1/auth/register': deleteRegister,
|
||||
})
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
overlayMock.resolveOpen(false)
|
||||
await flushPromises()
|
||||
|
||||
expect(deleteRegister).not.toHaveBeenCalled()
|
||||
expect(router.currentRoute.value.path).toBe('/register/pending')
|
||||
expect(wrapper.text()).toContain('Check your email')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancelled — 200 navigates to /register with a toast', () => {
|
||||
it('navigates to /register and shows the cancelled toast', async () => {
|
||||
const { wrapper } = await mountPending({
|
||||
'DELETE /v1/auth/register': () => mockResponse(200),
|
||||
})
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const props = overlayMock.getProps() as { action: () => Promise<void> }
|
||||
await props.action()
|
||||
overlayMock.resolveOpen(true)
|
||||
await flushPromises()
|
||||
|
||||
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('Already verified — 403 refreshes the session and navigates to /home with a toast', () => {
|
||||
it('awaits session.retry, navigates to /home and shows the info toast', async () => {
|
||||
const { wrapper } = await mountPending({
|
||||
'DELETE /v1/auth/register': () => mockResponse(403),
|
||||
'GET /v1/auth/me': () => mockResponse(200, { is_verified: true }),
|
||||
})
|
||||
const session = useSessionStore()
|
||||
session.session = { verified: false }
|
||||
session.status = 'ready'
|
||||
|
||||
const pushSpy = vi.spyOn(router, 'push')
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const props = overlayMock.getProps() as { action: () => Promise<void> }
|
||||
await props.action()
|
||||
|
||||
expect(session.session).toEqual({ verified: true })
|
||||
expect(pushSpy).not.toHaveBeenCalledWith('/register/pending')
|
||||
|
||||
overlayMock.resolveOpen(true)
|
||||
await flushPromises()
|
||||
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/home'))
|
||||
expect(toastAdd).toHaveBeenCalledWith({
|
||||
color: 'info',
|
||||
icon: 'i-lucide-info',
|
||||
title: 'Your account is already verified',
|
||||
description: "There's nothing to cancel.",
|
||||
})
|
||||
expect(pushSpy).not.toHaveBeenCalledWith('/register/pending')
|
||||
pushSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Cancel failed — the dialog stays open and shows the failure inline', () => {
|
||||
it.each([
|
||||
{ name: 'a 500 response', handler: () => mockResponse(500) },
|
||||
{
|
||||
name: 'a network failure',
|
||||
handler: () => Promise.reject(new TypeError('Failed to fetch')),
|
||||
},
|
||||
])('rejects the action instead of navigating for $name', async ({ handler }) => {
|
||||
const { wrapper } = await mountPending({
|
||||
'DELETE /v1/auth/register': handler,
|
||||
})
|
||||
|
||||
await findButton(wrapper, 'Cancel registration')?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const props = overlayMock.getProps() as { action: () => Promise<void> }
|
||||
await expect(props.action()).rejects.toThrow()
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/register/pending')
|
||||
expect(toastAdd).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -296,4 +296,19 @@ describe('A successful registration goes straight to the pending page', () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('writes the submitted email to sessionStorage before navigating', async () => {
|
||||
sessionStorage.removeItem('renewcms:pendingEmail')
|
||||
const { wrapper } = await mountRegister({
|
||||
'POST /v1/auth/register': () => mockResponse(200),
|
||||
'GET /v1/auth/me': () => mockResponse(200, { is_verified: false }),
|
||||
})
|
||||
|
||||
await fillValidForm(wrapper)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/register/pending'))
|
||||
|
||||
expect(sessionStorage.getItem('renewcms:pendingEmail')).toBe('marta@renew.example')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,377 @@
|
||||
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<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 toastAdd: ReturnType<typeof vi.fn>
|
||||
|
||||
vi.mock('@nuxt/ui/composables', () => ({
|
||||
useToast: () => ({ add: toastAdd }),
|
||||
}))
|
||||
|
||||
let currentWrapper: Awaited<ReturnType<typeof mount>> | null = null
|
||||
|
||||
async function mountVerify(
|
||||
path: string,
|
||||
handlers: Record<string, () => Response | Promise<Response>> = {},
|
||||
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<ReturnType<typeof mount>>, 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')
|
||||
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/home'), {
|
||||
timeout: 2000,
|
||||
})
|
||||
expect(toastAdd).toHaveBeenCalledWith({
|
||||
color: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: 'Your account is verified',
|
||||
description: 'Welcome to RenewCMS.',
|
||||
})
|
||||
|
||||
const session = useSessionStore()
|
||||
expect(session.session).toEqual({ verified: true })
|
||||
})
|
||||
})
|
||||
|
||||
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 — submit is disabled until both fields are filled', () => {
|
||||
it('enables the submit button once both fields have a value', async () => {
|
||||
const { wrapper } = await mountVerify('/register/validate?c=abc123', {
|
||||
'POST /v1/auth/verify': () => mockResponse(401),
|
||||
})
|
||||
|
||||
expect((wrapper.find('button[type="submit"]').element as HTMLButtonElement).disabled).toBe(
|
||||
true,
|
||||
)
|
||||
|
||||
await wrapper.find('input[placeholder="Your username"]').setValue('marta')
|
||||
await wrapper.find('input[autocomplete="current-password"]').setValue('limewash2026')
|
||||
|
||||
expect((wrapper.find('button[type="submit"]').element as HTMLButtonElement).disabled).toBe(
|
||||
false,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
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'))
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user