- Route CodeEditorField through codeeditor/load so vitest can mock the chunk - Keep registry expectations for colorpicker/codeeditor without importing the editor SFC Co-authored-by: Cursor <cursoragent@cursor.com>
495 lines
19 KiB
TypeScript
495 lines
19 KiB
TypeScript
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 codeeditorBundle = {
|
|
'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: '—' },
|
|
}
|
|
|
|
const mailPreviewBundle = {
|
|
...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.',
|
|
},
|
|
}
|
|
|
|
const PREVIEW = `${API}/mail/preview`
|
|
const TEST_SEND = `${API}/mail/test-send`
|
|
|
|
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(mailPreviewBundle, 'en')
|
|
clearToasts()
|
|
setCurrentUser(profile.data)
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
document.body.innerHTML = ''
|
|
clearToasts()
|
|
})
|
|
|
|
enableAutoUnmount(afterEach)
|
|
|
|
describe('MailPreviewField', () => {
|
|
it('binds a sandboxed srcdoc iframe to the server html only', async () => {
|
|
const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview('<p>Rendered</p>') })
|
|
const wrapper = mountPreview({ body: 'hi' })
|
|
await flushPromises()
|
|
|
|
const frame = wrapper.find('[data-mail-preview-frame]')
|
|
expect(frame.exists()).toBe(true)
|
|
expect(frame.attributes('sandbox')).toBe('')
|
|
expect(frame.attributes('src')).toBeUndefined()
|
|
expect(frame.attributes('srcdoc')).toBe('<p>Rendered</p>')
|
|
expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(1)
|
|
const body = await requestsTo(calls, 'POST', PREVIEW)[0]!.clone().json()
|
|
expect(body).toEqual({ mode: 'template', id: 3, values: { body: 'hi' } })
|
|
})
|
|
|
|
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>')
|
|
expect(wrapper.find('[data-mail-preview-subject]').text()).toContain('Second')
|
|
})
|
|
|
|
it('keeps the previous srcdoc after a 422 and shows the failed line', async () => {
|
|
let n = 0
|
|
mockApi({
|
|
[`POST ${PREVIEW}`]: () => {
|
|
n++
|
|
if (n === 1) {
|
|
return okPreview('<p>Good</p>')
|
|
}
|
|
return {
|
|
status: 422,
|
|
body: {
|
|
error: {
|
|
code: 'validation_failed',
|
|
message: 'Validation failed',
|
|
details: { field: 'body', rule: 'unsafe', message: 'script refused' },
|
|
},
|
|
},
|
|
}
|
|
},
|
|
})
|
|
const values = ref({ body: 'ok' })
|
|
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()
|
|
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Good</p>')
|
|
|
|
values.value = { body: 'bad' }
|
|
await wait(520)
|
|
await flushPromises()
|
|
|
|
expect(wrapper.find('[data-mail-preview-frame]').attributes('srcdoc')).toBe('<p>Good</p>')
|
|
expect(wrapper.find('[data-mail-preview-error]').text()).toContain('script refused')
|
|
})
|
|
|
|
it('disables the test-send button after a 429 with Retry-After', async () => {
|
|
mockApi({
|
|
[`POST ${PREVIEW}`]: okPreview(),
|
|
[`POST ${TEST_SEND}`]: {
|
|
status: 429,
|
|
headers: { 'Retry-After': '30' },
|
|
body: { error: { code: 'rate_limited', message: 'Too many', details: {} } },
|
|
},
|
|
})
|
|
const wrapper = mountPreview({ body: 'hi' })
|
|
await flushPromises()
|
|
|
|
await wrapper.find('[data-mail-preview-test-send]').trigger('click')
|
|
await flushPromises()
|
|
|
|
const button = wrapper.find('[data-mail-preview-test-send]')
|
|
expect(button.attributes('disabled')).toBeDefined()
|
|
expect(wrapper.find('[data-mail-preview-test-error]').text()).toContain('30')
|
|
})
|
|
|
|
it('sends nothing for an empty draft', async () => {
|
|
const calls = mockApi({ [`POST ${PREVIEW}`]: okPreview() })
|
|
const wrapper = mountPreview({ body: ' ' })
|
|
await flushPromises()
|
|
|
|
expect(requestsTo(calls, 'POST', PREVIEW)).toHaveLength(0)
|
|
expect(wrapper.find('[data-mail-preview-empty]').exists()).toBe(true)
|
|
expect(wrapper.find('[data-mail-preview-frame]').exists()).toBe(false)
|
|
})
|
|
|
|
it('toasts the returned email on a successful test send', 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')
|
|
})
|
|
})
|
|
|
|
function codeField(overrides: Partial<FormField> = {}): FormField {
|
|
return {
|
|
name: 'content_html',
|
|
label: 'HTML',
|
|
type: 'codeeditor',
|
|
language: 'html',
|
|
size: 'large',
|
|
...overrides,
|
|
} as FormField
|
|
}
|
|
|
|
describe('CodeEditorField loading and fallback', () => {
|
|
beforeEach(() => {
|
|
setBundle({ ...mailPreviewBundle, ...codeeditorBundle }, 'en')
|
|
})
|
|
|
|
it('shows the bg-skel loading box at the size height while the chunk loads', async () => {
|
|
// Hold the chunk import open so the loading box stays visible.
|
|
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: codeField(), 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()
|
|
wrapper.unmount()
|
|
vi.doUnmock('../../src/components/form/codeeditor/load')
|
|
})
|
|
|
|
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: codeField({ readOnly: true }),
|
|
modelValue: 'layout {{ name }}',
|
|
controlId: 'f-html',
|
|
},
|
|
attachTo: document.body,
|
|
})
|
|
await flushPromises()
|
|
const pre = wrapper.find('pre')
|
|
expect(pre.exists()).toBe(true)
|
|
expect(pre.text()).toBe('layout {{ name }}')
|
|
expect(wrapper.find('[data-codeeditor-loading]').exists()).toBe(false)
|
|
expect(wrapper.find('.cm-editor').exists()).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('insertImage', () => {
|
|
it('escapes markdown, html, css and text snippets per UI-SPEC C4', async () => {
|
|
const { insertImage } = await import('../../src/components/mail/insertImage')
|
|
expect(insertImage('markdown', 'https://cdn.example.com/a b.png', 'Logo [x]')).toBe(
|
|
'![Logo \\[x\\]](https://cdn.example.com/a%20b.png)',
|
|
)
|
|
expect(insertImage('html', 'https://cdn.example.com/a"b.png', 'a "b" <c>')).toBe(
|
|
'<img src="https://cdn.example.com/a"b.png" alt="a "b" <c>">',
|
|
)
|
|
expect(insertImage('css', 'https://cdn.example.com/a.png', 'ignored')).toBe(
|
|
'url("https://cdn.example.com/a.png")',
|
|
)
|
|
expect(insertImage('text', 'https://cdn.example.com/a.png', 'ignored')).toBe(
|
|
'https://cdn.example.com/a.png',
|
|
)
|
|
})
|
|
})
|
|
|
|
const pickerBundle = {
|
|
...mailPreviewBundle,
|
|
...codeeditorBundle,
|
|
'backend::lang.colorpicker.pick': { other: 'Pick a colour for “:field”' },
|
|
'backend::lang.colorpicker.not_set': { other: 'Not set' },
|
|
'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.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.form.cancel': { other: 'Cancel' },
|
|
}
|
|
|
|
describe('ColorPickerField', () => {
|
|
it('syncs a typed #rrggbb into the swatch and keeps the last valid on partial', async () => {
|
|
const Field = (await import('../../src/components/form/fields/ColorPickerField.vue')).default
|
|
setBundle(pickerBundle, 'en')
|
|
const wrapper = mount(Field, {
|
|
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')
|
|
})
|
|
})
|
|
|
|
describe('MailImagePicker and MarkdownField mailImages', () => {
|
|
beforeEach(() => {
|
|
setBundle(pickerBundle, 'en')
|
|
})
|
|
|
|
it('shows the upload row only when meta.canUpload is true', async () => {
|
|
const Picker = (await import('../../src/components/mail/MailImagePicker.vue')).default
|
|
mockApi({
|
|
[`GET ${API}/mail/images`]: {
|
|
body: { data: [], meta: { canUpload: false, total: 0, page: 1, perPage: 40 } },
|
|
},
|
|
})
|
|
const wrapper = mount(Picker, {
|
|
props: { open: true, mode: 'insert' },
|
|
attachTo: document.body,
|
|
})
|
|
await flushPromises()
|
|
expect(document.querySelector('[data-mail-image-upload]')).toBeNull()
|
|
|
|
mockApi({
|
|
[`GET ${API}/mail/images`]: {
|
|
body: { data: [], meta: { canUpload: true, total: 0, page: 1, perPage: 40 } },
|
|
},
|
|
})
|
|
await wrapper.setProps({ open: false })
|
|
await flushPromises()
|
|
await wrapper.setProps({ open: true })
|
|
await flushPromises()
|
|
expect(document.querySelector('[data-mail-image-upload]')).not.toBeNull()
|
|
})
|
|
|
|
it('hides Preview and inserts markdown at the caret when mailImages is set', async () => {
|
|
const Field = (await import('../../src/components/form/fields/MarkdownField.vue')).default
|
|
mockApi({
|
|
[`GET ${API}/mail/images`]: {
|
|
body: {
|
|
data: [{ id: 9, fileName: 'logo.png', title: 'Logo', url: 'https://cdn.example.com/logo.png' }],
|
|
meta: { canUpload: false, total: 1, page: 1, perPage: 40 },
|
|
},
|
|
},
|
|
})
|
|
const wrapper = mount(Field, {
|
|
props: {
|
|
field: { name: 'body', label: 'Body', type: 'markdown', mailImages: true } as FormField,
|
|
modelValue: 'Hello ',
|
|
controlId: 'f-body',
|
|
},
|
|
attachTo: document.body,
|
|
})
|
|
expect(wrapper.find('[data-markdown-preview]').exists()).toBe(false)
|
|
expect(wrapper.find('[data-markdown-insert-image]').exists()).toBe(true)
|
|
await wrapper.find('[data-markdown-insert-image]').trigger('click')
|
|
await flushPromises()
|
|
const tile = document.querySelector<HTMLElement>('[data-mail-image-id="9"]')
|
|
expect(tile).not.toBeNull()
|
|
tile!.click()
|
|
await flushPromises()
|
|
document.querySelector<HTMLElement>('[data-mail-image-confirm]')!.click()
|
|
await flushPromises()
|
|
expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual(['Hello '])
|
|
})
|
|
})
|
|
|
|
describe('MailImageField', () => {
|
|
it('shows the missing line when the stored id is gone', async () => {
|
|
;(await import('../../src/app/i18n')).setBundle(pickerBundle, 'en')
|
|
const Field = (await import('../../src/components/form/fields/MailImageField.vue')).default
|
|
mockApi({
|
|
[`GET ${API}/mail/images/3`]: { status: 404, body: { error: { code: 'not_found', message: 'gone', details: {} } } },
|
|
})
|
|
const wrapper = mount(Field, {
|
|
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')
|
|
})
|
|
})
|
|
|
|
// Last in the file: it replaces the editor chunk for the rest of the run.
|
|
describe('CodeEditorField chunk failure', () => {
|
|
afterEach(() => {
|
|
vi.doUnmock('../../src/components/form/codeeditor/editor')
|
|
vi.resetModules()
|
|
})
|
|
|
|
it('shows the load_failed note and a monospace textarea that still emits', async () => {
|
|
vi.resetModules()
|
|
vi.doUnmock('../../src/components/form/codeeditor/load')
|
|
vi.doMock('../../src/components/form/codeeditor/load', () => ({
|
|
importCodeEditor: async () => {
|
|
throw new Error('chunk failed')
|
|
},
|
|
}))
|
|
;(await import('../../src/app/i18n')).setBundle({ ...mailPreviewBundle, ...codeeditorBundle }, 'en')
|
|
const Field = (await import('../../src/components/form/fields/CodeEditorField.vue')).default
|
|
const wrapper = mount(Field, {
|
|
props: { field: codeField(), modelValue: '<p>Stored</p>', controlId: 'f-html' },
|
|
attachTo: document.body,
|
|
})
|
|
await vi.waitFor(() => {
|
|
expect(wrapper.find('[data-codeeditor-load-failed]').exists()).toBe(true)
|
|
})
|
|
expect(wrapper.find('[data-codeeditor-load-failed]').text()).toContain('could not be loaded')
|
|
const textarea = wrapper.find<HTMLTextAreaElement>('textarea')
|
|
expect(textarea.exists()).toBe(true)
|
|
expect(textarea.element.value).toBe('<p>Stored</p>')
|
|
expect(textarea.attributes('id')).toBe('f-html')
|
|
await textarea.setValue('<p>Edited</p>')
|
|
expect(wrapper.emitted('update:modelValue')).toEqual([['<p>Edited</p>']])
|
|
})
|
|
})
|
|
|
|
describe('RowStateBadges mail states', () => {
|
|
it('renders customized then outdated after the existing three', async () => {
|
|
const Badges = (await import('../../src/components/list/RowStateBadges.vue')).default
|
|
const wrapper = mount(Badges, {
|
|
props: {
|
|
states: ['outdated', 'customized', 'disabled', 'deleted'],
|
|
labels: {
|
|
deleted: 'Deleted',
|
|
negative: 'Negative',
|
|
disabled: 'Disabled',
|
|
customized: 'Customized',
|
|
outdated: 'File changed',
|
|
},
|
|
},
|
|
})
|
|
expect(wrapper.findAll('[data-row-state]').map((node) => node.attributes('data-row-state'))).toEqual([
|
|
'deleted',
|
|
'disabled',
|
|
'customized',
|
|
'outdated',
|
|
])
|
|
})
|
|
})
|