test(admin): unit and browser tests for the mail editor fields

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-13 14:23:28 +01:00
parent 45017039b2
commit 1ae1a9553f
12 changed files with 1009 additions and 9 deletions

View File

@@ -0,0 +1,119 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import type { FormField } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import { langFixture } from '../fixtures/typed'
import { resetState } from '../helpers'
const bundle = {
...langFixture.data,
'backend::lang.codeeditor.load_failed': {
other: 'The code editor could not be loaded. You can still edit the text here.',
},
'backend::lang.codeeditor.toolbar': { other: 'Code editor tools' },
'backend::lang.list.empty_value': { other: '—' },
}
function field(overrides: Partial<FormField> = {}): FormField {
return {
name: 'content_html',
label: 'HTML',
type: 'codeeditor',
language: 'html',
size: 'large',
...overrides,
} as FormField
}
beforeEach(() => {
resetState()
setBundle(bundle, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
vi.doUnmock('../../src/components/form/codeeditor/load')
vi.resetModules()
})
enableAutoUnmount(afterEach)
describe('CodeEditorField', () => {
it('shows the loading box at the size height while the chunk loads', async () => {
let release!: () => void
const gate = new Promise<void>((resolve) => {
release = resolve
})
vi.resetModules()
vi.doMock('../../src/components/form/codeeditor/load', () => ({
importCodeEditor: async () => {
await gate
return await vi.importActual('../../src/components/form/codeeditor/editor')
},
}))
const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default
const wrapper = mount(Field, {
props: { field: field(), modelValue: '<p>x</p>', controlId: 'f-html' },
attachTo: document.body,
})
await flushPromises()
const loading = wrapper.find('[data-codeeditor-loading]')
expect(loading.exists()).toBe(true)
expect(loading.attributes('aria-busy')).toBe('true')
expect((loading.element as HTMLElement).style.height).toBe('320px')
release()
await flushPromises()
})
it('renders a read-only pre without loading CodeMirror', async () => {
const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default
const wrapper = mount(Field, {
props: {
field: field({ readOnly: true }),
modelValue: 'layout {{ name }}',
controlId: 'f-html',
},
attachTo: document.body,
})
await flushPromises()
expect(wrapper.find('pre').text()).toBe('layout {{ name }}')
expect(wrapper.find('.cm-editor').exists()).toBe(false)
})
it('falls back to a monospace textarea when the chunk fails', async () => {
vi.resetModules()
vi.doMock('../../src/components/form/codeeditor/load', () => ({
importCodeEditor: async () => {
throw new Error('chunk failed')
},
}))
const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default
const wrapper = mount(Field, {
props: { field: field(), modelValue: '<p>Stored</p>', controlId: 'f-html' },
attachTo: document.body,
})
await vi.waitFor(() => {
expect(wrapper.find('[data-codeeditor-load-failed]').exists()).toBe(true)
})
const textarea = wrapper.find<HTMLTextAreaElement>('textarea')
expect(textarea.element.value).toBe('<p>Stored</p>')
await textarea.setValue('<p>Edited</p>')
expect(wrapper.emitted('update:modelValue')).toEqual([['<p>Edited</p>']])
})
it('replaces an external modelValue without emitting', async () => {
const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default
const wrapper = mount(Field, {
props: {
field: field({ language: 'text', size: 'small' }),
modelValue: 'one',
controlId: 'f-text',
},
attachTo: document.body,
})
await flushPromises()
await wrapper.setProps({ modelValue: 'two' })
await flushPromises()
expect(wrapper.emitted('update:modelValue') ?? []).toEqual([])
})
})

View File

@@ -0,0 +1,58 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { enableAutoUnmount, mount } from '@vue/test-utils'
import type { FormField } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import ColorPickerField from '../../src/components/form/fields/ColorPickerField.vue'
import { langFixture } from '../fixtures/typed'
import { resetState } from '../helpers'
const bundle = {
...langFixture.data,
'backend::lang.colorpicker.pick': { other: 'Pick a colour for “:field”' },
'backend::lang.colorpicker.not_set': { other: 'Not set' },
}
beforeEach(() => {
resetState()
setBundle(bundle, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('ColorPickerField (UI-SPEC C2)', () => {
it('syncs a typed #rrggbb into the swatch and keeps the last valid on partial', async () => {
const wrapper = mount(ColorPickerField, {
props: {
field: { name: 'body_bg', label: 'Body background', type: 'colorpicker' } as FormField,
modelValue: '',
controlId: 'f-color',
},
attachTo: document.body,
})
const text = wrapper.find<HTMLInputElement>('input[type="text"]')
const swatch = wrapper.find<HTMLInputElement>('input[type="color"]')
expect(swatch.element.value).toBe('#ffffff')
await text.setValue('#D66829')
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['#D66829'])
expect(swatch.element.value.toLowerCase()).toBe('#d66829')
await text.setValue('#D66')
expect(swatch.element.value.toLowerCase()).toBe('#d66829')
})
it('clears to empty when the text is blank', async () => {
const wrapper = mount(ColorPickerField, {
props: {
field: { name: 'body_bg', label: 'Body background', type: 'colorpicker' } as FormField,
modelValue: '#112233',
controlId: 'f-color',
},
attachTo: document.body,
})
await wrapper.find('input[type="text"]').setValue('')
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([''])
})
})

View File

@@ -0,0 +1,143 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { enableAutoUnmount, flushPromises } from '@vue/test-utils'
import { setBundle } from '../../src/app/i18n'
import { toasts } from '../../src/state/useToasts'
import { clone, formSchemaFixture, langFixture, recordFixture } from '../fixtures/typed'
import { API, mountApp, resetState, type Reply, type Route } from '../helpers'
const BASE = `${API}/summercms/cabana/mailtemplates`
const RECORD = `${BASE}/7`
const strings = {
'backend::lang.form.action_confirm': { other: 'Run “:action” on this record?' },
'backend::lang.form.action_done': { other: 'Action completed.' },
'backend::lang.form.action_stale': { other: 'This action no longer applies to this record.' },
'backend::lang.list.action_forbidden': { other: 'You do not have permission to run this action.' },
'backend::lang.extension.action_failed': { other: 'The action could not be completed.' },
'backend::lang.form.delete_confirm': { other: 'Delete this record?' },
}
function mailSchema() {
const envelope = clone(formSchemaFixture)
envelope.data.fields = [
{ name: 'subject', label: 'Subject', type: 'text' },
{ name: 'body', label: 'Body', type: 'textarea' },
] as typeof envelope.data.fields
return { body: envelope }
}
function mailRecord(meta: Record<string, unknown> = {}): Reply {
const envelope = clone(recordFixture)
envelope.data = { id: 7, subject: 'Hello', body: 'Body' }
envelope.meta = {
...envelope.meta,
actions: [{ name: 'reset', label: 'Reset to file', confirm: 'Discard customizations?', danger: true }],
deletable: false,
...meta,
}
return { body: envelope }
}
function routes(overrides: Record<string, Route> = {}): Record<string, Route> {
return {
[`GET ${BASE}/schema/form`]: mailSchema(),
[`GET ${RECORD}`]: mailRecord(),
...overrides,
}
}
beforeEach(() => {
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('FormView mail footer actions and meta.deletable', () => {
it('offers reset with a danger confirm, then toasts and reloads', async () => {
let gets = 0
const { wrapper } = await mountApp(
'/summercms/cabana/mailtemplates/7',
routes({
[`GET ${RECORD}`]: () => {
gets++
if (gets === 1) {
return mailRecord()
}
return mailRecord({ actions: [] })
},
[`POST ${RECORD}/actions/reset`]: { body: { data: { message: 'Restored from file.', fill: {} }, meta: {} } },
}),
)
expect(wrapper.find('[data-record-action="reset"]').exists()).toBe(true)
expect(wrapper.find('[data-action="delete"]').exists()).toBe(false)
await wrapper.find('[data-record-action="reset"]').trigger('click')
await flushPromises()
const dialog = document.body.querySelector<HTMLElement>('[data-confirm-dialog]')
expect(dialog?.textContent).toContain('Discard customizations?')
dialog!.querySelector<HTMLButtonElement>('[data-action="confirm"]')!.click()
await flushPromises()
expect(toasts.value.some((toast) => toast.text.includes('Restored from file.'))).toBe(true)
})
it('honours meta.deletable true and absent (default true for non-mail fixtures)', async () => {
const deletable = await mountApp(
'/summercms/cabana/mailtemplates/7',
routes({ [`GET ${RECORD}`]: mailRecord({ deletable: true, actions: [] }) }),
)
expect(deletable.wrapper.find('[data-action="delete"]').exists()).toBe(true)
const absent = await mountApp(
'/summercms/cabana/mailtemplates/7',
routes({
[`GET ${RECORD}`]: (() => {
const envelope = clone(recordFixture)
envelope.data = { id: 7, subject: 'Hello', body: 'Body' }
envelope.meta = { ...(envelope.meta ?? {}), actions: [] }
delete (envelope.meta as { deletable?: boolean }).deletable
return { body: envelope }
})(),
}),
)
expect(absent.wrapper.find('[data-action="delete"]').exists()).toBe(true)
})
it('toasts 403 and 409 paths from record actions', async () => {
const forbidden = await mountApp(
'/summercms/cabana/mailtemplates/7',
routes({
[`POST ${RECORD}/actions/reset`]: {
status: 403,
body: { error: { code: 'forbidden', message: '', details: {} } },
},
}),
)
await forbidden.wrapper.find('[data-record-action="reset"]').trigger('click')
await flushPromises()
document.body.querySelector<HTMLButtonElement>('[data-action="confirm"]')!.click()
await flushPromises()
expect(toasts.value.some((toast) => toast.text.includes('permission'))).toBe(true)
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
const stale = await mountApp(
'/summercms/cabana/mailtemplates/7',
routes({
[`POST ${RECORD}/actions/reset`]: {
status: 409,
body: { error: { code: 'conflict', message: 'gone', details: {} } },
},
}),
)
await stale.wrapper.find('[data-record-action="reset"]').trigger('click')
await flushPromises()
document.body.querySelector<HTMLButtonElement>('[data-action="confirm"]')!.click()
await flushPromises()
expect(toasts.value.some((toast) => toast.text.includes('no longer applies'))).toBe(true)
})
})

View File

@@ -0,0 +1,73 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import type { FormField } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import MailImageField from '../../src/components/form/fields/MailImageField.vue'
import { langFixture } from '../fixtures/typed'
import { API, mockApi, resetState } from '../helpers'
const bundle = {
...langFixture.data,
'backend::lang.mailimage.empty': { other: 'No image chosen' },
'backend::lang.mailimage.choose': { other: 'Choose image' },
'backend::lang.mailimage.change': { other: 'Change image' },
'backend::lang.mailimage.remove': { other: 'Remove image' },
'backend::lang.mailimage.missing': {
other: 'This image is no longer in the library. Choose another one.',
},
'backend::lang.mail.picker.choose_title': { other: 'Choose an image' },
'backend::lang.mail.picker.search': { other: 'Search images' },
'backend::lang.mail.picker.use': { other: 'Use this image' },
'backend::lang.mail.picker.upload': { other: 'Upload image' },
'backend::lang.mail.picker.empty_title': { other: 'No images yet' },
'backend::lang.mail.picker.empty_pick_only': { other: 'Images are added in Settings.' },
'backend::lang.mail.picker.load_failed': { other: 'The image library could not be loaded.' },
'backend::lang.form.cancel': { other: 'Cancel' },
}
beforeEach(() => {
resetState()
setBundle(bundle, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('MailImageField (UI-SPEC C11)', () => {
it('shows the missing line when the stored id is gone', async () => {
mockApi({
[`GET ${API}/mail/images/3`]: {
status: 404,
body: { error: { code: 'not_found', message: 'gone', details: {} } },
},
})
const wrapper = mount(MailImageField, {
props: {
field: { name: 'logo', label: 'Logo', type: 'mailimage' } as FormField,
modelValue: 3,
controlId: 'f-logo',
},
attachTo: document.body,
})
await flushPromises()
expect(wrapper.find('[data-mailimage-missing]').exists()).toBe(true)
expect(wrapper.find('[data-mailimage-missing]').text()).toContain('no longer in the library')
})
it('shows empty copy when no image is chosen', async () => {
const wrapper = mount(MailImageField, {
props: {
field: { name: 'logo', label: 'Logo', type: 'mailimage' } as FormField,
modelValue: null,
controlId: 'f-logo',
},
attachTo: document.body,
})
await flushPromises()
expect(wrapper.text()).toContain('No image chosen')
expect(wrapper.find('[data-mailimage-missing]').exists()).toBe(false)
})
})

View File

@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import { setBundle } from '../../src/app/i18n'
import MailImagePicker from '../../src/components/mail/MailImagePicker.vue'
import { langFixture } from '../fixtures/typed'
import { API, mockApi, resetState, type Reply } from '../helpers'
const bundle = {
...langFixture.data,
'backend::lang.mail.picker.insert_button': { other: 'Insert image' },
'backend::lang.mail.picker.insert_title': { other: 'Insert an image from the library' },
'backend::lang.mail.picker.choose_title': { other: 'Choose an image' },
'backend::lang.mail.picker.search': { other: 'Search images' },
'backend::lang.mail.picker.insert': { other: 'Insert image' },
'backend::lang.mail.picker.use': { other: 'Use this image' },
'backend::lang.mail.picker.upload': { other: 'Upload image' },
'backend::lang.mail.picker.uploading': { other: 'Uploading…' },
'backend::lang.mail.picker.empty_title': { other: 'No images yet' },
'backend::lang.mail.picker.empty_upload': { other: 'Upload an image to use it in mail.' },
'backend::lang.mail.picker.empty_pick_only': { other: 'Images are added in Settings.' },
'backend::lang.mail.picker.no_results': { other: 'No images match “:query”.' },
'backend::lang.mail.picker.load_failed': { other: 'The image library could not be loaded.' },
'backend::lang.mail.picker.alt': { other: 'Alternative text' },
'backend::lang.mail.picker.alt_comment': { other: 'Describes the image.' },
'backend::lang.form.cancel': { other: 'Cancel' },
}
function listReply(opts: {
canUpload?: boolean
data?: unknown[]
status?: number
message?: string
} = {}): Reply {
if (opts.status && opts.status >= 400) {
return {
status: opts.status,
body: { error: { code: 'x', message: opts.message ?? 'failed', details: {} } },
}
}
return {
body: {
data: opts.data ?? [],
meta: { canUpload: opts.canUpload ?? false, total: (opts.data ?? []).length, page: 1, perPage: 40 },
},
}
}
beforeEach(() => {
resetState()
setBundle(bundle, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
async function openPicker(mode: 'insert' | 'choose') {
const wrapper = mount(MailImagePicker, {
props: { open: false, mode },
attachTo: document.body,
})
await flushPromises()
await wrapper.setProps({ open: true })
await flushPromises()
return wrapper
}
describe('MailImagePicker', () => {
it('shows the upload row only when meta.canUpload is true', async () => {
mockApi({ [`GET ${API}/mail/images`]: listReply({ canUpload: false }) })
const wrapper = await openPicker('insert')
expect(document.querySelector('[data-mail-image-upload]')).toBeNull()
expect(document.body.textContent).toContain('Images are added in Settings.')
mockApi({ [`GET ${API}/mail/images`]: listReply({ canUpload: true }) })
await wrapper.setProps({ open: false })
await flushPromises()
await wrapper.setProps({ open: true })
await flushPromises()
expect(document.querySelector('[data-mail-image-upload]')).not.toBeNull()
expect(document.body.textContent).toContain('Upload an image to use it in mail.')
})
it('shows load failed copy when the library request fails', async () => {
mockApi({ [`GET ${API}/mail/images`]: listReply({ status: 500, message: 'boom' }) })
await openPicker('choose')
expect(document.querySelector('[data-mail-image-load-failed]')?.textContent).toContain(
'The image library could not be loaded.',
)
})
it('disables primary until a tile is chosen; insert prefills alt from title', async () => {
mockApi({
[`GET ${API}/mail/images`]: listReply({
canUpload: false,
data: [{ id: 9, fileName: 'logo.png', title: 'Logo', url: 'https://cdn.example.com/logo.png' }],
}),
})
const wrapper = await openPicker('insert')
const confirm = document.querySelector<HTMLButtonElement>('[data-mail-image-confirm]')
expect(confirm?.disabled).toBe(true)
document.querySelector<HTMLElement>('[data-mail-image-id="9"]')!.click()
await flushPromises()
expect(confirm?.disabled).toBe(false)
const alt = document.querySelector<HTMLInputElement>('[data-mail-image-alt]')
expect(alt?.value).toBe('Logo')
confirm!.click()
await flushPromises()
expect(wrapper.emitted('insert')?.at(-1)).toEqual([{ url: 'https://cdn.example.com/logo.png', alt: 'Logo' }])
})
it('choose mode emits the id and has no alt field', async () => {
mockApi({
[`GET ${API}/mail/images`]: listReply({
data: [{ id: 4, fileName: 'a.png', title: 'A', url: 'https://cdn.example.com/a.png' }],
}),
})
const wrapper = await openPicker('choose')
expect(document.querySelector('[data-mail-image-alt]')).toBeNull()
document.querySelector<HTMLElement>('[data-mail-image-id="4"]')!.click()
await flushPromises()
document.querySelector<HTMLButtonElement>('[data-mail-image-confirm]')!.click()
await flushPromises()
expect(wrapper.emitted('choose')?.at(-1)).toEqual([4])
})
})

View File

@@ -0,0 +1,237 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import { computed, ref } from 'vue'
import type { FormField } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import MailPreviewField from '../../src/components/form/fields/MailPreviewField.vue'
import { FORM_VALUES } from '../../src/components/form/formContext'
import { setCurrentUser } from '../../src/state/useAuth'
import { clearToasts, toasts } from '../../src/state/useToasts'
import { API, mockApi, profile, requestsTo, resetState, type Reply, wait } from '../helpers'
import { langFixture } from '../fixtures/typed'
const PREVIEW = `${API}/mail/preview`
const TEST_SEND = `${API}/mail/test-send`
const bundle = {
...langFixture.data,
'backend::lang.mail.preview.html': { other: 'HTML' },
'backend::lang.mail.preview.text': { other: 'Plain text' },
'backend::lang.mail.preview.subject': { other: 'Subject' },
'backend::lang.mail.preview.frame_title': { other: 'Preview of the HTML message' },
'backend::lang.mail.preview.rendering': { other: 'Rendering preview…' },
'backend::lang.mail.preview.empty': { other: 'Nothing to preview yet. Write the message first.' },
'backend::lang.mail.preview.failed': {
other: 'The draft cannot be rendered: :message The preview shows the last version that rendered.',
},
'backend::lang.mail.preview.failed_first': { other: 'The draft cannot be rendered: :message' },
'backend::lang.mail.preview.unavailable': { other: 'Preview unavailable. It updates again with your next edit.' },
'backend::lang.mail.preview.sample_note': {
other: 'Variables are filled with sample values. A variable without a sample shows as [name].',
},
'backend::lang.mail.preview.sample_content_note': { other: 'Previewed with sample content.' },
'backend::lang.mail.preview.test_send': { other: 'Send test to me' },
'backend::lang.mail.preview.test_sending': { other: 'Sending…' },
'backend::lang.mail.preview.test_hint': {
other: 'Sends the current draft, unsaved changes included, to :email.',
},
'backend::lang.mail.preview.test_sent': { other: 'Test message sent to :email.' },
'backend::lang.mail.preview.test_limited': {
other: 'You have sent too many test messages. Try again in :seconds s.',
},
'backend::lang.mail.preview.test_invalid': { other: 'Fix the draft before sending a test: :message' },
'backend::lang.mail.preview.test_failed': {
other: 'The test message could not be sent. Check the mail settings and the application log.',
},
}
function previewField(mode = 'template'): FormField {
return { name: '_preview', label: 'Preview', type: 'mailpreview', mode } as FormField
}
function okPreview(html = '<p>Hello</p>', subject = 'Welcome', text = 'Hello'): Reply {
return { body: { data: { html, subject, text }, meta: {} } }
}
function mountPreview(values: Record<string, unknown>, field: FormField = previewField(), recordId: number | null = 3) {
const valuesRef = ref(values)
return mount(MailPreviewField, {
props: { field, modelValue: null, controlId: 'f-preview', recordId },
global: { provide: { [FORM_VALUES as symbol]: computed(() => valuesRef.value) } },
attachTo: document.body,
})
}
beforeEach(() => {
resetState()
setBundle(bundle, 'en')
clearToasts()
setCurrentUser(profile.data)
})
afterEach(() => {
vi.useRealTimers()
document.body.innerHTML = ''
clearToasts()
})
enableAutoUnmount(afterEach)
describe('MailPreviewField', () => {
it('uses an empty sandbox and srcdoc only, never src', async () => {
mockApi({ [`POST ${PREVIEW}`]: okPreview('<p>Rendered</p>') })
const wrapper = mountPreview({ body: 'hi' })
await flushPromises()
const frame = wrapper.find('[data-mail-preview-frame]')
expect(frame.attributes('sandbox')).toBe('')
expect(frame.attributes('src')).toBeUndefined()
expect(frame.attributes('srcdoc')).toBe('<p>Rendered</p>')
})
it('drops a stale preview answer via the sequence guard', async () => {
let resolveFirst!: (reply: Reply) => void
const first = new Promise<Reply>((resolve) => {
resolveFirst = resolve
})
let calls = 0
mockApi({
[`POST ${PREVIEW}`]: async () => {
calls++
if (calls === 1) {
return first
}
return okPreview('<p>Second</p>', 'Second')
},
})
const values = ref({ body: 'one' })
const wrapper = mount(MailPreviewField, {
props: { field: previewField(), modelValue: null, controlId: 'f-preview', recordId: 1 },
global: { provide: { [FORM_VALUES as symbol]: computed(() => values.value) } },
attachTo: document.body,
})
await flushPromises()
values.value = { body: 'two' }
await wait(520)
await flushPromises()
resolveFirst(okPreview('<p>First</p>', 'First'))
await flushPromises()
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Second</p>')
})
it('shows failed_first when the first render fails', async () => {
mockApi({
[`POST ${PREVIEW}`]: {
status: 422,
body: {
error: {
code: 'validation_failed',
message: 'Validation failed',
details: { field: 'body', rule: 'parse', message: 'unclosed' },
},
},
},
})
const wrapper = mountPreview({ body: 'bad' })
await flushPromises()
expect(wrapper.find('[data-mail-preview-error]').text()).toContain('unclosed')
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc') ?? '').toBe('')
})
it('shows unavailable on a 5xx preview', async () => {
mockApi({
[`POST ${PREVIEW}`]: { status: 503, body: { error: { code: 'x', message: 'down', details: {} } } },
})
const wrapper = mountPreview({ body: 'hi' })
await flushPromises()
expect(wrapper.find('[data-mail-preview-error]').text()).toContain('Preview unavailable')
})
it('sends nothing for an empty draft or when the preview is off-screen', async () => {
const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview() })
mountPreview({ body: ' ' })
await flushPromises()
expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(0)
const callbacks: IntersectionObserverCallback[] = []
const Original = globalThis.IntersectionObserver
globalThis.IntersectionObserver = class {
constructor(cb: IntersectionObserverCallback) {
callbacks.push(cb)
}
observe() {
callbacks.at(-1)?.(
[{ isIntersecting: false, target: document.body } as unknown as IntersectionObserverEntry],
this as unknown as IntersectionObserver,
)
}
unobserve() {}
disconnect() {}
takeRecords() {
return []
}
root = null
rootMargin = ''
thresholds = []
} as typeof IntersectionObserver
const calls2 = mockApi({ [`POST ${PREVIEW}`]: okPreview() })
mountPreview({ body: 'visible draft' })
await flushPromises()
expect(requestsTo(calls2, 'POST', PREVIEW)).toHaveLength(0)
globalThis.IntersectionObserver = Original
})
it('branding mode has no subject row and no test send', async () => {
mockApi({ [`POST ${PREVIEW}`]: okPreview('<style>.a{}</style>', '', '') })
const wrapper = mountPreview({ button_primary_bg: '#112233' }, previewField('branding'), null)
await flushPromises()
expect(wrapper.find('[data-mail-preview-subject]').exists()).toBe(false)
expect(wrapper.find('[data-mail-preview-test-send]').exists()).toBe(false)
})
it('toasts on 2xx test send; disables after 429; shows 422 inline', async () => {
mockApi({
[`POST ${PREVIEW}`]: okPreview(),
[`POST ${TEST_SEND}`]: { body: { data: { email: 'dev@example.test' }, meta: {} } },
})
const wrapper = mountPreview({ body: 'hi' })
await flushPromises()
await wrapper.find('[data-mail-preview-test-send]').trigger('click')
await flushPromises()
expect(toasts.value[0]?.text).toContain('dev@example.test')
mockApi({
[`POST ${PREVIEW}`]: okPreview(),
[`POST ${TEST_SEND}`]: {
status: 429,
headers: { 'Retry-After': '30' },
body: { error: { code: 'rate_limited', message: 'Too many', details: {} } },
},
})
const limited = mountPreview({ body: 'hi' })
await flushPromises()
await limited.find('[data-mail-preview-test-send]').trigger('click')
await flushPromises()
expect(limited.find('[data-mail-preview-test-send]').attributes('disabled')).toBeDefined()
expect(limited.find('[data-mail-preview-test-error]').text()).toContain('30')
mockApi({
[`POST ${PREVIEW}`]: okPreview(),
[`POST ${TEST_SEND}`]: {
status: 422,
body: {
error: {
code: 'validation_failed',
message: 'Validation failed',
details: { field: 'body', rule: 'unsafe', message: 'script' },
},
},
},
})
const invalid = mountPreview({ body: 'hi' })
await flushPromises()
await invalid.find('[data-mail-preview-test-send]').trigger('click')
await flushPromises()
expect(invalid.find('[data-mail-preview-test-error]').text()).toContain('script')
})
})

View File

@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { insertImage } from '../../src/components/mail/insertImage'
describe('insertImage (UI-SPEC C4)', () => {
it.each([
[
'markdown',
'https://cdn.example.com/a b(c).png',
'Logo [x]',
'![Logo \\[x\\]](https://cdn.example.com/a%20b%28c%29.png)',
],
[
'html',
'https://cdn.example.com/a"b.png',
'a "b" <c>',
'<img src="https://cdn.example.com/a&quot;b.png" alt="a &quot;b&quot; &lt;c&gt;">',
],
['css', 'https://cdn.example.com/a.png', 'ignored', 'url("https://cdn.example.com/a.png")'],
['text', 'https://cdn.example.com/a.png', 'ignored', 'https://cdn.example.com/a.png'],
] as const)('builds %s snippets with escaping', (language, url, alt, want) => {
expect(insertImage(language, url, alt)).toBe(want)
})
it('handles empty alt and parentheses in markdown URLs', () => {
expect(insertImage('markdown', 'https://cdn.example.com/x(y).png', '')).toBe(
'![](https://cdn.example.com/x%28y%29.png)',
)
expect(insertImage('html', 'https://cdn.example.com/x.png', '')).toBe(
'<img src="https://cdn.example.com/x.png" alt="">',
)
})
})

View File

@@ -59,7 +59,9 @@ describe('field renderer registry (D-05)', () => {
expect(isRegistered('codeeditor')).toBe(true)
expect(needsRecord('codeeditor')).toBe(false)
expect(rendererFor('codeeditor')).not.toBe(UnsupportedField)
expect(rendererFor('codeeditor').__name).toBe('CodeEditorField')
expect((rendererFor('codeeditor') as { name?: string; __name?: string }).name ?? (rendererFor('codeeditor') as { __name?: string }).__name).toBe(
'CodeEditorField',
)
})
it.each(['notatype', '', 'TEXT', 'constructor'])('falls back to UnsupportedField for %j', (type) => {