feat: register T0
This commit is contained in:
1 parent
a5873f8886
commit
3c3f7c6194
9 files changed
+920
-4
No files matched your search
@@ -60,6 +60,9 @@ const colorModeSelectUi = { trailing: 'hidden' }
|
||||
watch(
|
||||
() => props.title,
|
||||
(title) => {
|
||||
if (!title) {
|
||||
return
|
||||
}
|
||||
document.title = `${title} · RenewCMS`
|
||||
},
|
||||
{ immediate: true },
|
||||
@@ -67,7 +70,10 @@ watch(
|
||||
|
||||
watch(
|
||||
() => props.title,
|
||||
() => {
|
||||
(title) => {
|
||||
if (!title) {
|
||||
return
|
||||
}
|
||||
titleEl.value?.focus()
|
||||
},
|
||||
)
|
||||
@@ -86,7 +92,7 @@ watch(
|
||||
<AppLogo :size="32" />
|
||||
</template>
|
||||
|
||||
<template #title>
|
||||
<template v-if="title" #title>
|
||||
<h1 ref="titleEl" tabindex="-1" class="outline-none">{{ title }}</h1>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
interface PasswordRule {
|
||||
label: string
|
||||
met: boolean
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
rules: PasswordRule[]
|
||||
showErrors: boolean
|
||||
}>()
|
||||
|
||||
function itemClass(rule: PasswordRule) {
|
||||
if (rule.met) {
|
||||
return 'text-success'
|
||||
}
|
||||
return props.showErrors ? 'text-error' : 'text-toned'
|
||||
}
|
||||
|
||||
function itemIcon(rule: PasswordRule) {
|
||||
if (rule.met) {
|
||||
return 'i-lucide-circle-check'
|
||||
}
|
||||
return props.showErrors ? 'i-lucide-circle-alert' : 'i-lucide-circle'
|
||||
}
|
||||
|
||||
const items = computed(() =>
|
||||
props.rules.map((rule) => ({
|
||||
...rule,
|
||||
classes: itemClass(rule),
|
||||
icon: itemIcon(rule),
|
||||
})),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul class="flex flex-col gap-1">
|
||||
<li
|
||||
v-for="item in items"
|
||||
:key="item.label"
|
||||
:class="['flex items-center gap-1.5 text-sm', item.classes]"
|
||||
>
|
||||
<UIcon :name="item.icon" class="shrink-0" />
|
||||
{{ item.label }}
|
||||
<span class="sr-only">{{ item.met ? 'met' : 'not met' }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</template>
|
||||
@@ -0,0 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
|
||||
interface ResultPanelAction {
|
||||
label: string
|
||||
color?: 'primary' | 'neutral'
|
||||
variant?: 'solid' | 'soft' | 'outline' | 'ghost'
|
||||
to?: string
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
tone: 'success' | 'error' | 'info'
|
||||
icon: string
|
||||
title: string
|
||||
description: string
|
||||
actions: ResultPanelAction[]
|
||||
}>()
|
||||
|
||||
const role = computed(() => (props.tone === 'error' ? 'alert' : 'status'))
|
||||
|
||||
const toneTileClass: Record<'success' | 'error' | 'info', string> = {
|
||||
success: 'bg-success/10 text-success',
|
||||
error: 'bg-error/10 text-error',
|
||||
info: 'bg-info/10 text-info',
|
||||
}
|
||||
|
||||
const tileClass = computed(() => toneTileClass[props.tone])
|
||||
|
||||
const titleEl = ref<HTMLHeadingElement | null>(null)
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
titleEl.value?.focus()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :role="role" class="flex flex-col gap-4">
|
||||
<div :class="['flex h-11 w-11 items-center justify-center', tileClass]">
|
||||
<UIcon :name="icon" class="h-6 w-6" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<h1 ref="titleEl" tabindex="-1" class="text-xl font-semibold leading-7 outline-none">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<p class="text-toned text-sm">{{ description }}</p>
|
||||
</div>
|
||||
<div class="flex w-full flex-col gap-2">
|
||||
<UButton
|
||||
v-for="action in actions"
|
||||
:key="action.label"
|
||||
block
|
||||
size="lg"
|
||||
:color="action.color ?? 'primary'"
|
||||
:variant="action.variant ?? 'solid'"
|
||||
:to="action.to"
|
||||
@click="action.onClick"
|
||||
>
|
||||
{{ action.label }}
|
||||
</UButton>
|
||||
</div>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -29,6 +29,28 @@ describe('AuthShell renders its title as the page heading and sets the document
|
||||
})
|
||||
})
|
||||
|
||||
describe('AuthShell with an empty title renders no heading and leaves document.title untouched', () => {
|
||||
it('mounts directly with an empty title without rendering an h1 or touching document.title', () => {
|
||||
document.title = 'Existing title · RenewCMS'
|
||||
|
||||
const wrapper = mountShell({ title: '' })
|
||||
|
||||
expect(wrapper.find('h1').exists()).toBe(false)
|
||||
expect(document.title).toBe('Existing title · RenewCMS')
|
||||
})
|
||||
|
||||
it('leaves document.title untouched and does not crash when the title changes to empty', async () => {
|
||||
const wrapper = mountShell({ title: 'Create the owner account' })
|
||||
|
||||
expect(document.title).toBe('Create the owner account · RenewCMS')
|
||||
|
||||
await wrapper.setProps({ title: '' })
|
||||
|
||||
expect(wrapper.find('h1').exists()).toBe(false)
|
||||
expect(document.title).toBe('Create the owner account · RenewCMS')
|
||||
})
|
||||
})
|
||||
|
||||
describe('AuthShell renders its notice and footer slots', () => {
|
||||
it('renders the notice slot as-is inside the card, after the title, and the footer slot outside the card', () => {
|
||||
const wrapper = mountShell(
|
||||
|
||||
@@ -1,9 +1,246 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { 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 EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
const router = useRouter()
|
||||
const api = useApi()
|
||||
|
||||
const username = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
|
||||
const usernameTouched = ref(false)
|
||||
const emailTouched = ref(false)
|
||||
const passwordTouched = ref(false)
|
||||
|
||||
const submitting = ref(false)
|
||||
const passwordShown = ref(false)
|
||||
const registrationClosed = ref(false)
|
||||
const serverErrorAlert = ref(false)
|
||||
|
||||
const usernameValid = computed(() => username.value.length >= 3 && username.value.length <= 20)
|
||||
const emailValid = computed(() => EMAIL_PATTERN.test(email.value))
|
||||
const passwordValid = computed(() => password.value.length >= 8)
|
||||
|
||||
const usernameError = computed(() =>
|
||||
usernameTouched.value && !usernameValid.value ? 'Use 3 to 20 characters.' : '',
|
||||
)
|
||||
|
||||
const emailError = computed(() =>
|
||||
emailTouched.value && !emailValid.value
|
||||
? 'Enter a full email address, like name@example.com.'
|
||||
: '',
|
||||
)
|
||||
|
||||
const passwordRules = computed(() => [{ label: 'At least 8 characters', met: passwordValid.value }])
|
||||
|
||||
const formValid = computed(() => usernameValid.value && emailValid.value && passwordValid.value)
|
||||
|
||||
function touchAll() {
|
||||
usernameTouched.value = true
|
||||
emailTouched.value = true
|
||||
passwordTouched.value = true
|
||||
}
|
||||
|
||||
function goToLogin() {
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
async function onSubmit() {
|
||||
touchAll()
|
||||
|
||||
if (!formValid.value) {
|
||||
return
|
||||
}
|
||||
|
||||
serverErrorAlert.value = false
|
||||
submitting.value = true
|
||||
try {
|
||||
await api.request('/v1/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: username.value,
|
||||
email: email.value,
|
||||
password: password.value,
|
||||
}),
|
||||
})
|
||||
await router.push('/register/pending')
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 403) {
|
||||
registrationClosed.value = true
|
||||
document.title = 'This site already has an owner · RenewCMS'
|
||||
return
|
||||
}
|
||||
serverErrorAlert.value = true
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const pageTitle = computed(() => (registrationClosed.value ? '' : 'Create the owner account'))
|
||||
|
||||
const pageDescription = computed(() =>
|
||||
registrationClosed.value
|
||||
? undefined
|
||||
: "This creates the single admin account for this site. Once it's verified, registration closes.",
|
||||
)
|
||||
|
||||
const closedPanelActions = [{ label: 'Go to log in', onClick: goToLogin }]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AuthShell title="Create your account">
|
||||
<p>Register placeholder.</p>
|
||||
<AuthShell :title="pageTitle" :description="pageDescription">
|
||||
<template v-if="serverErrorAlert" #notice>
|
||||
<UAlert
|
||||
color="error"
|
||||
icon="i-lucide-circle-x"
|
||||
title="Couldn't create the account"
|
||||
description="Something went wrong on the server. Try again in a moment."
|
||||
variant="soft"
|
||||
:close="false"
|
||||
role="alert"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-if="registrationClosed" #default>
|
||||
<ResultPanel
|
||||
tone="info"
|
||||
icon="i-lucide-user-x"
|
||||
title="This site already has an owner"
|
||||
description="Log in instead."
|
||||
:actions="closedPanelActions"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else #default="{ controlSize, controlClass }">
|
||||
<UForm
|
||||
:state="{ username, email, password }"
|
||||
class="flex flex-col gap-4"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<UFormField
|
||||
label="Username"
|
||||
name="username"
|
||||
:error="usernameError || undefined"
|
||||
:size="controlSize"
|
||||
>
|
||||
<template v-if="usernameError" #error="{ error }">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<UIcon name="i-lucide-circle-alert" class="text-error shrink-0" />
|
||||
{{ error }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else #help>
|
||||
Letters and numbers, 3 to 20 characters. You'll use it to log in.
|
||||
</template>
|
||||
<template #hint>
|
||||
<span :class="usernameError ? 'text-error' : 'text-toned'">
|
||||
{{ username.length }} / 20
|
||||
</span>
|
||||
</template>
|
||||
<UInput
|
||||
v-model="username"
|
||||
placeholder="e.g. marta"
|
||||
autocomplete="username"
|
||||
:disabled="submitting"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
:highlight="!!usernameError"
|
||||
:size="controlSize"
|
||||
:ui="{ base: controlClass }"
|
||||
class="w-full"
|
||||
@blur="usernameTouched = true"
|
||||
/>
|
||||
</UFormField>
|
||||
|
||||
<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="text-error shrink-0" />
|
||||
{{ error }}
|
||||
</span>
|
||||
</template>
|
||||
<template v-else #help> We'll send a verification link here. </template>
|
||||
<UInput
|
||||
v-model="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
autocomplete="email"
|
||||
:disabled="submitting"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
:highlight="!!emailError"
|
||||
:size="controlSize"
|
||||
:ui="{ base: controlClass }"
|
||||
class="w-full"
|
||||
@blur="emailTouched = true"
|
||||
/>
|
||||
</UFormField>
|
||||
|
||||
<UFormField label="Password" name="password" :size="controlSize">
|
||||
<template #help>
|
||||
<PasswordStrengthHint
|
||||
:rules="passwordRules"
|
||||
:show-errors="passwordTouched"
|
||||
/>
|
||||
</template>
|
||||
<UInput
|
||||
v-model="password"
|
||||
:type="passwordShown ? 'text' : 'password'"
|
||||
autocomplete="new-password"
|
||||
:disabled="submitting"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
:size="controlSize"
|
||||
:ui="{ base: controlClass }"
|
||||
class="w-full"
|
||||
@blur="passwordTouched = true"
|
||||
>
|
||||
<template #trailing>
|
||||
<UButton
|
||||
:icon="passwordShown ? 'i-lucide-eye-off' : 'i-lucide-eye'"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
square
|
||||
:aria-label="passwordShown ? 'Hide password' : 'Show password'"
|
||||
:aria-pressed="passwordShown"
|
||||
@click="passwordShown = !passwordShown"
|
||||
/>
|
||||
</template>
|
||||
</UInput>
|
||||
</UFormField>
|
||||
|
||||
<UButton
|
||||
type="submit"
|
||||
block
|
||||
:size="controlSize"
|
||||
:ui="{ base: controlClass }"
|
||||
:loading="submitting"
|
||||
:disabled="submitting"
|
||||
>
|
||||
{{ submitting ? 'Creating account…' : 'Create account' }}
|
||||
</UButton>
|
||||
</UForm>
|
||||
</template>
|
||||
|
||||
<template v-if="!registrationClosed" #footer>
|
||||
<p>
|
||||
Already set up?
|
||||
<RouterLink to="/login" class="text-primary">Log in</RouterLink>
|
||||
</p>
|
||||
</template>
|
||||
</AuthShell>
|
||||
</template>
|
||||
@@ -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 ResultPanel from '@/components/ResultPanel.vue'
|
||||
import RegisterView from '../RegisterView.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 mountRegister(handlers: Record<string, () => Response | Promise<Response>> = {}) {
|
||||
setActivePinia(createPinia())
|
||||
const fetchMock = fetchRouter(handlers)
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
await router.push('/register')
|
||||
const wrapper = mount(RegisterView, {
|
||||
attachTo: document.body,
|
||||
global: {
|
||||
plugins: [router, uiPlugin],
|
||||
},
|
||||
})
|
||||
currentWrapper = wrapper
|
||||
await flushPromises()
|
||||
return { wrapper, fetchMock }
|
||||
}
|
||||
|
||||
function usernameInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
|
||||
return wrapper.find('input[placeholder="e.g. marta"]')
|
||||
}
|
||||
|
||||
function emailInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
|
||||
return wrapper.find('input[placeholder="you@example.com"]')
|
||||
}
|
||||
|
||||
function passwordInput(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
|
||||
return wrapper.find('input[autocomplete="new-password"]')
|
||||
}
|
||||
|
||||
async function fillValidForm(wrapper: Awaited<ReturnType<typeof mountRegister>>) {
|
||||
await usernameInput(wrapper).setValue('marta')
|
||||
await emailInput(wrapper).setValue('marta@renew.example')
|
||||
await passwordInput(wrapper).setValue('limewash2026')
|
||||
}
|
||||
|
||||
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 mountRegister()
|
||||
|
||||
expect(wrapper.find('h1').text()).toBe('Create the owner account')
|
||||
expect(wrapper.text()).toContain(
|
||||
"This creates the single admin account for this site. Once it's verified, registration closes.",
|
||||
)
|
||||
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('')
|
||||
expect(wrapper.text()).toContain('0 / 20')
|
||||
|
||||
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('')
|
||||
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('')
|
||||
expect(wrapper.text()).toContain('At least 8 characters')
|
||||
|
||||
expect(wrapper.find('button[type="submit"]').text()).toBe('Create account')
|
||||
expect(wrapper.text()).toContain('Already set up?')
|
||||
const footerLink = wrapper.find('a[href="/login"]')
|
||||
expect(footerLink.exists()).toBe(true)
|
||||
expect(footerLink.text()).toBe('Log in')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Validation errors — checked on blur and on submit', () => {
|
||||
it('shows the three errors and never calls the register endpoint', async () => {
|
||||
const register = vi.fn(() => mockResponse(200))
|
||||
const { wrapper } = await mountRegister({
|
||||
'POST /v1/auth/register': register,
|
||||
})
|
||||
|
||||
await usernameInput(wrapper).setValue('ma')
|
||||
await usernameInput(wrapper).trigger('blur')
|
||||
|
||||
await emailInput(wrapper).setValue('marta@renew')
|
||||
await emailInput(wrapper).trigger('blur')
|
||||
|
||||
await passwordInput(wrapper).setValue('lime')
|
||||
await passwordInput(wrapper).trigger('blur')
|
||||
|
||||
expect(wrapper.text()).toContain('2 / 20')
|
||||
expect(wrapper.text()).toContain('Use 3 to 20 characters.')
|
||||
expect(wrapper.text()).toContain('Enter a full email address, like name@example.com.')
|
||||
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(register).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('Use 3 to 20 characters.')
|
||||
expect(wrapper.text()).toContain('Enter a full email address, like name@example.com.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Filled, valid — every rule is met', () => {
|
||||
it('shows no errors and a green checklist item', async () => {
|
||||
const { wrapper } = await mountRegister()
|
||||
|
||||
await fillValidForm(wrapper)
|
||||
|
||||
const toggle = wrapper.find('button[aria-label="Show password"]')
|
||||
await toggle.trigger('click')
|
||||
|
||||
expect(wrapper.find('button[aria-label="Hide password"]').attributes('aria-pressed')).toBe(
|
||||
'true',
|
||||
)
|
||||
|
||||
expect(wrapper.text()).toContain('5 / 20')
|
||||
expect(wrapper.text()).not.toContain('Use 3 to 20 characters.')
|
||||
expect(wrapper.text()).toContain(
|
||||
"Letters and numbers, 3 to 20 characters. You'll use it to log in.",
|
||||
)
|
||||
|
||||
expect(wrapper.text()).not.toContain('Enter a full email address, like name@example.com.')
|
||||
expect(wrapper.text()).toContain("We'll send a verification link here.")
|
||||
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).type).toBe('text')
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
|
||||
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Create account')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Submitting — fields and button are disabled while the request is in flight', () => {
|
||||
it('disables the fields and shows the loading label', async () => {
|
||||
let resolveRegister: (() => void) | null = null
|
||||
const { wrapper } = await mountRegister({
|
||||
'POST /v1/auth/register': () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRegister = () => resolve(mockResponse(200))
|
||||
}),
|
||||
})
|
||||
|
||||
await fillValidForm(wrapper)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
|
||||
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).disabled).toBe(true)
|
||||
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Creating account…')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(true)
|
||||
|
||||
resolveRegister?.()
|
||||
await flushPromises()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Registration closed — the form is replaced by a ResultPanel', () => {
|
||||
it('shows the panel and navigates to /login when activated', async () => {
|
||||
const { wrapper, fetchMock } = await mountRegister({
|
||||
'POST /v1/auth/register': () => mockResponse(403),
|
||||
})
|
||||
|
||||
await fillValidForm(wrapper)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/auth/register',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
username: 'marta',
|
||||
email: 'marta@renew.example',
|
||||
password: 'limewash2026',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(wrapper.find('form').exists()).toBe(false)
|
||||
expect(wrapper.text()).toContain('This site already has an owner')
|
||||
expect(wrapper.text()).toContain('Log in instead.')
|
||||
expect(wrapper.text()).not.toContain('Already set up?')
|
||||
expect(document.title).toBe('This site already has an owner · RenewCMS')
|
||||
|
||||
const resultPanel = wrapper.findComponent(ResultPanel)
|
||||
expect(resultPanel.props('tone')).toBe('info')
|
||||
expect(resultPanel.props('icon')).toBe('i-lucide-user-x')
|
||||
|
||||
const action = wrapper.find('button')
|
||||
expect(action.text()).toBe('Go to log in')
|
||||
await action.trigger('click')
|
||||
|
||||
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('Server or network error — the form is kept and re-enabled', () => {
|
||||
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 register = vi.fn(handler)
|
||||
const { wrapper, fetchMock } = await mountRegister({
|
||||
'POST /v1/auth/register': register,
|
||||
})
|
||||
|
||||
await fillValidForm(wrapper)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/auth/register',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
username: 'marta',
|
||||
email: 'marta@renew.example',
|
||||
password: 'limewash2026',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
expect(wrapper.text()).toContain("Couldn't create the account")
|
||||
expect(wrapper.text()).toContain(
|
||||
'Something went wrong on the server. Try again in a moment.',
|
||||
)
|
||||
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).value).toBe('marta')
|
||||
expect((emailInput(wrapper).element as HTMLInputElement).value).toBe('marta@renew.example')
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).value).toBe('limewash2026')
|
||||
|
||||
expect((usernameInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
|
||||
expect((emailInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
|
||||
expect((passwordInput(wrapper).element as HTMLInputElement).disabled).toBe(false)
|
||||
|
||||
const submitButton = wrapper.find('button[type="submit"]')
|
||||
expect(submitButton.text()).toBe('Create account')
|
||||
expect((submitButton.element as HTMLButtonElement).disabled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('A successful registration goes straight to the pending page', () => {
|
||||
it('navigates directly to /register/pending on submit resolution', async () => {
|
||||
const { wrapper, fetchMock } = 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(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/auth/register',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
username: 'marta',
|
||||
email: 'marta@renew.example',
|
||||
password: 'limewash2026',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -38,6 +38,31 @@ function loginWith(response: ApiMock, path = '/login'): Omit<VisualState, 'steps
|
||||
}
|
||||
}
|
||||
|
||||
async function fillRegister(page: Page, username: string, email: string, password: string) {
|
||||
await page.getByPlaceholder('e.g. marta').fill(username)
|
||||
await page.getByPlaceholder('e.g. marta').blur()
|
||||
await page.getByPlaceholder('you@example.com').fill(email)
|
||||
await page.getByPlaceholder('you@example.com').blur()
|
||||
await page.locator('input[autocomplete="new-password"]').fill(password)
|
||||
await page.locator('input[autocomplete="new-password"]').blur()
|
||||
}
|
||||
|
||||
function registerWith(response: ApiMock): Omit<VisualState, 'steps'> {
|
||||
return {
|
||||
path: '/register',
|
||||
api: {
|
||||
'POST /v1/auth/register': response,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function submitRegister(username: string, email: string, password: string) {
|
||||
return async (page: Page) => {
|
||||
await fillRegister(page, username, email, password)
|
||||
await page.getByRole('button', { name: 'Create account', exact: true }).click()
|
||||
}
|
||||
}
|
||||
|
||||
export const visualStates: Record<string, Record<string, VisualState>> = {
|
||||
'log-in': {
|
||||
Default: { path: '/login', api: { 'GET /v1/auth/registration': registrationClosed } },
|
||||
@@ -74,4 +99,32 @@ export const visualStates: Record<string, Record<string, VisualState>> = {
|
||||
steps: submitLogin('marta', 'limewash2026'),
|
||||
},
|
||||
},
|
||||
register: {
|
||||
Default: { path: '/register' },
|
||||
'Validation errors': {
|
||||
path: '/register',
|
||||
steps: async (page) => {
|
||||
await fillRegister(page, 'ma', 'marta@renew', 'lime')
|
||||
},
|
||||
},
|
||||
'Filled, valid': {
|
||||
path: '/register',
|
||||
steps: async (page) => {
|
||||
await fillRegister(page, 'marta', 'marta@renew.example', 'limewash2026')
|
||||
await page.getByRole('button', { name: 'Show password' }).click()
|
||||
},
|
||||
},
|
||||
Submitting: {
|
||||
...registerWith({ status: 200, hang: true }),
|
||||
steps: submitRegister('marta', 'marta@renew.example', 'limewash2026'),
|
||||
},
|
||||
'Registration closed (403)': {
|
||||
...registerWith({ status: 403 }),
|
||||
steps: submitRegister('marta', 'marta@renew.example', 'limewash2026'),
|
||||
},
|
||||
'Server error': {
|
||||
...registerWith({ status: 500 }),
|
||||
steps: submitRegister('marta', 'marta@renew.example', 'limewash2026'),
|
||||
},
|
||||
},
|
||||
}
|
||||
Reference in new issue
Block a user