238 lines
9.1 KiB
TypeScript
238 lines
9.1 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 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')
|
|
})
|
|
})
|