308 lines
14 KiB
TypeScript
308 lines
14 KiB
TypeScript
import { generationConfigApi } from '@/features/generation-config/api'
|
||
import { imageCatalog, generationProfile } from '../../fixtures/generation'
|
||
import { routerLinkStubs } from '../../fixtures/router'
|
||
import { defineComponent, h, reactive } from 'vue'
|
||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||
import { NFormItem, NInput, NSelect } from 'naive-ui'
|
||
import AppForm from '@/components/ui/AppForm.vue'
|
||
import CreateProjectDialog from '@/features/projects/components/CreateProjectDialog.vue'
|
||
import GenerateImageDialog from '@/features/subject-images/components/GenerateImageDialog.vue'
|
||
import StyleEditor from '@/features/visual-style/components/StyleEditor.vue'
|
||
import StyleImages from '@/features/visual-style/components/StyleImages.vue'
|
||
import { formFixture } from '@/features/subject-images/testing/fixtures'
|
||
import { requiredTextRule } from '@/lib/form-rules'
|
||
|
||
/** 当前测试使用真实目录契约构造项目模型配置。 */
|
||
const creativeProfile = generationProfile('gallery-test')
|
||
/** 生成提交由测试替身接收,绝不调用真实模型。 */
|
||
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
|
||
let wrapper: VueWrapper | undefined
|
||
afterEach(() => {
|
||
submitGeneration.mockClear()
|
||
wrapper?.unmount()
|
||
wrapper = undefined
|
||
document.body.innerHTML = ''
|
||
vi.restoreAllMocks()
|
||
vi.unstubAllGlobals()
|
||
})
|
||
/**
|
||
* 查找真实弹窗的可见操作按钮。
|
||
* @param text 按钮完整文案
|
||
* @returns 实际按钮元素
|
||
*/
|
||
function button(text: string) {
|
||
const result = [...document.querySelectorAll<HTMLButtonElement>('button')].find(
|
||
el => el.textContent?.trim() === text
|
||
)
|
||
if (!result) throw new Error(`找不到按钮:${text}`)
|
||
return result
|
||
}
|
||
/**
|
||
* 更新真实表单字段并等待 Vue 绑定同步。
|
||
* @param selector 字段选择器
|
||
* @param value 本次输入值
|
||
* @returns 字段绑定同步完成
|
||
*/
|
||
async function input(selector: string, value: string) {
|
||
const el = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(selector)!
|
||
el.value = value
|
||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||
await flushPromises()
|
||
}
|
||
/**
|
||
* 汇总实际字段错误反馈。
|
||
* @returns 当前全部校验错误文案
|
||
*/
|
||
function feedback() {
|
||
return [...document.querySelectorAll('.n-form-item-feedback--error')].map(el => el.textContent).join(' ')
|
||
}
|
||
/**
|
||
* 提交实际表单以执行统一字段校验。
|
||
* @returns 表单校验与响应同步完成
|
||
*/
|
||
async function submit() {
|
||
document.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
|
||
await flushPromises()
|
||
}
|
||
|
||
describe('统一的 Naive UI 表单校验', () => {
|
||
it('新建剧本使用字段反馈拦截空白主题和小数集数,修正后只发送一次请求', async () => {
|
||
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
|
||
new Response('{"projectId":"created","executionId":"create-execution-1","status":"pending"}', {
|
||
status: 202
|
||
})
|
||
)
|
||
vi.stubGlobal('fetch', fetcher)
|
||
wrapper = mount(CreateProjectDialog, { attachTo: document.body })
|
||
button('新建剧本').click()
|
||
await flushPromises()
|
||
expect(document.querySelector('form')!.noValidate).toBe(true)
|
||
expect(document.querySelector('[required]')).toBeNull()
|
||
await input('#title', ' 雨夜来信标题 ')
|
||
await input('#topic', ' ')
|
||
const focus = vi.spyOn(HTMLTextAreaElement.prototype, 'focus')
|
||
button('开始生成').click()
|
||
await flushPromises()
|
||
expect(feedback()).toContain('请填写故事主题')
|
||
// 无布局的 DOM 环境会被模态框焦点圈带回哨兵,检查实际聚焦目标。
|
||
expect(focus.mock.contexts).toContain(document.querySelector('#topic'))
|
||
expect(fetcher).not.toHaveBeenCalled()
|
||
await input('#topic', ' 雨夜来信 ')
|
||
await input('#episode-count', '1.5')
|
||
button('开始生成').click()
|
||
await flushPromises()
|
||
expect(feedback()).toContain('计划集数须为正整数')
|
||
expect(fetcher).not.toHaveBeenCalled()
|
||
await input('#episode-count', '3')
|
||
expect(feedback()).toBe('')
|
||
button('开始生成').click()
|
||
button('开始生成').click()
|
||
await flushPromises()
|
||
expect(fetcher).toHaveBeenCalledTimes(1)
|
||
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({
|
||
title: '雨夜来信标题',
|
||
topic: '雨夜来信',
|
||
style: '',
|
||
/** 与后端 Auto 时长预算契约一致,不再发送旧的顶层集数。 */
|
||
durationBudget: { mode: 'auto', episodeCount: 3 }
|
||
})
|
||
expect(wrapper.emitted('created')).toEqual([['created', 'create-execution-1']])
|
||
})
|
||
|
||
it('图片尺寸采用目录必填枚举,切换目标清空提示词和费用确认', async () => {
|
||
/** 原图片表单先解析主体覆盖,测试仅提供正式只读配置。 */
|
||
vi.spyOn(generationConfigApi, 'resolve').mockResolvedValue({
|
||
provider: creativeProfile.imageProvider,
|
||
model: creativeProfile.imageModel,
|
||
options: { ...creativeProfile.imageOptions }
|
||
})
|
||
wrapper = mount(GenerateImageDialog, {
|
||
attachTo: document.body,
|
||
props: {
|
||
submitGeneration,
|
||
open: true,
|
||
form: formFixture(),
|
||
disabled: false,
|
||
catalog: imageCatalog,
|
||
profile: creativeProfile
|
||
}
|
||
})
|
||
await flushPromises()
|
||
const size = wrapper.findAllComponents(NSelect).find(select => select.props('value') === '2048*2048')!
|
||
expect(size.props('clearable')).toBe(false)
|
||
expect(size.props('options')).toEqual([{ label: '1:1 · 2048×2048', value: '2048*2048' }])
|
||
expect(document.querySelector('#image-width')).toBeNull()
|
||
expect(document.querySelector('#image-height')).toBeNull()
|
||
await input('#image-prompt', '仅用于上一形态')
|
||
document.querySelector<HTMLElement>('#confirm-image-cost')!.click()
|
||
await flushPromises()
|
||
expect(button('确认生成图片').disabled).toBe(true)
|
||
await wrapper.setProps({ form: { ...formFixture(), id: 'other-form' } })
|
||
await flushPromises()
|
||
expect(document.querySelector<HTMLTextAreaElement>('#image-prompt')?.value).toBe('')
|
||
expect(button('确认生成图片').disabled).toBe(true)
|
||
expect(feedback()).toBe('')
|
||
expect(wrapper.emitted('generate')).toBeUndefined()
|
||
})
|
||
|
||
it('画面要求按行填写,保存时保持原有文字列表格式', async () => {
|
||
wrapper = mount(StyleEditor, { attachTo: document.body, props: { visualStyle: null, disabled: false } })
|
||
await flushPromises()
|
||
expect(wrapper.find('button[aria-expanded]').exists()).toBe(false)
|
||
expect(wrapper.get('.style-category-section h3').text()).toBe('分类风格与画面要求')
|
||
expect(wrapper.findAll('.style-category-fields .n-form-item')).toHaveLength(3)
|
||
await input('#style-name', '手工风格')
|
||
await input('#style-constraints', '真人写实\n\n 只用古代服装 ')
|
||
await submit()
|
||
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({
|
||
name: '手工风格',
|
||
hardConstraints: ['真人写实', '只用古代服装']
|
||
})
|
||
expect(wrapper.get('#style-constraints').isVisible()).toBe(true)
|
||
})
|
||
|
||
it('登记参考图拦截非法地址和小数排序,允许有效存储地址与负整数排序', async () => {
|
||
wrapper = mount(StyleImages, {
|
||
attachTo: document.body,
|
||
global: { stubs: routerLinkStubs },
|
||
props: { projectId: 'form-test-project', images: [], disabled: false }
|
||
})
|
||
expect(document.querySelector('[aria-label="风格图片地址"]')).toBeNull()
|
||
expect(wrapper.text()).not.toContain('先保存视觉风格')
|
||
button('通过链接添加').click()
|
||
await flushPromises()
|
||
await input('[aria-label="风格图片地址"]', 'javascript:alert(1)')
|
||
await input('[aria-label="风格图片排序"]', '1.5')
|
||
await submit()
|
||
expect(feedback()).toContain('请填写可访问的图片链接或已上传图片的地址')
|
||
expect(feedback()).toContain('排序须为整数')
|
||
expect(wrapper.emitted('add')).toBeUndefined()
|
||
await input('[aria-label="风格图片地址"]', '/storage/style.png')
|
||
await input('[aria-label="风格图片排序"]', '-1')
|
||
await submit()
|
||
expect(wrapper.emitted('add')?.[0]?.[0]).toMatchObject({ imageUrl: '/storage/style.png', sortOrder: -1 })
|
||
})
|
||
|
||
it('按需读取项目资产并用正式素材 ID 登记风格参考图', async () => {
|
||
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
|
||
new Response(
|
||
JSON.stringify({
|
||
data: [
|
||
{
|
||
id: 'asset-db-1',
|
||
projectId: 'form-test-project',
|
||
name: '人物质感参考',
|
||
type: 'image',
|
||
category: 'character',
|
||
mimeType: 'image/png',
|
||
extension: 'png',
|
||
size: 1024,
|
||
publicUrl: '/storage/reference.png',
|
||
metadata: null,
|
||
createdAt: '2026-09-21T00:00:00Z',
|
||
updatedAt: '2026-09-21T00:00:00Z'
|
||
}
|
||
]
|
||
})
|
||
)
|
||
)
|
||
vi.stubGlobal('fetch', fetcher)
|
||
wrapper = mount(StyleImages, {
|
||
attachTo: document.body,
|
||
global: { stubs: routerLinkStubs },
|
||
props: { projectId: 'form-test-project', images: [], disabled: false }
|
||
})
|
||
|
||
expect(fetcher).not.toHaveBeenCalled()
|
||
button('从资产库添加').click()
|
||
await flushPromises()
|
||
expect(fetcher).toHaveBeenCalledWith(
|
||
'/api/projects/form-test-project/assets',
|
||
expect.objectContaining({ method: 'GET' })
|
||
)
|
||
const option = document.querySelector<HTMLButtonElement>('.style-asset-option')!
|
||
expect(option.textContent).toContain('人物质感参考')
|
||
option.click()
|
||
await flushPromises()
|
||
await input('[aria-label="风格图片排序"]', '1.5')
|
||
await submit()
|
||
expect(feedback()).toContain('排序须为整数')
|
||
expect(wrapper.emitted('add')).toBeUndefined()
|
||
await input('[aria-label="风格图片排序"]', '-1')
|
||
await submit()
|
||
expect(document.querySelector('[aria-label="风格图片地址"]')).toBeNull()
|
||
expect(wrapper.emitted('add')?.[0]?.[0]).toMatchObject({
|
||
projectAssetId: 'asset-db-1',
|
||
category: 'overall',
|
||
source: 'upload'
|
||
})
|
||
})
|
||
|
||
it('未保存风格时禁用两个入口,资产读取失败可在弹窗重试', async () => {
|
||
const fetcher = vi
|
||
.fn<typeof fetch>()
|
||
.mockResolvedValueOnce(new Response('{"message":"素材读取失败"}', { status: 500 }))
|
||
.mockResolvedValue(new Response('{"data":[]}'))
|
||
vi.stubGlobal('fetch', fetcher)
|
||
wrapper = mount(StyleImages, {
|
||
attachTo: document.body,
|
||
global: { stubs: routerLinkStubs },
|
||
props: { projectId: 'form-test-project', images: [], disabled: true, hasStyle: false }
|
||
})
|
||
expect(wrapper.text()).toContain('先保存视觉风格')
|
||
expect(button('从资产库添加').disabled).toBe(true)
|
||
expect(button('通过链接添加').disabled).toBe(true)
|
||
await wrapper.setProps({ disabled: false, hasStyle: true })
|
||
button('从资产库添加').click()
|
||
await flushPromises()
|
||
expect(document.querySelector('.app-dialog')?.textContent).toContain('素材读取失败')
|
||
expect(button('添加参考图').disabled).toBe(true)
|
||
button('重试读取素材').click()
|
||
await flushPromises()
|
||
expect(document.querySelector('.app-dialog')?.textContent).toContain('资产库暂无图片')
|
||
expect(fetcher).toHaveBeenCalledTimes(2)
|
||
})
|
||
|
||
it('异步验证期间切换对象或重复提交不会执行旧动作', async () => {
|
||
let finish: (() => void) | undefined
|
||
const model = reactive({ text: '有效输入' })
|
||
const onSubmit = vi.fn<() => void>()
|
||
wrapper = mount(
|
||
defineComponent({
|
||
props: { target: { type: String, default: 'first' } },
|
||
setup(props) {
|
||
return () =>
|
||
h(
|
||
AppForm,
|
||
{
|
||
model,
|
||
resetKey: props.target,
|
||
onSubmit,
|
||
rules: {
|
||
text: {
|
||
...requiredTextRule('文本'),
|
||
asyncValidator: () =>
|
||
new Promise<void>(resolve => {
|
||
finish = resolve
|
||
})
|
||
}
|
||
}
|
||
},
|
||
() => h(NFormItem, { path: 'text', label: '文本' }, () => h(NInput, { value: model.text }))
|
||
)
|
||
}
|
||
}),
|
||
{ attachTo: document.body }
|
||
)
|
||
const form = document.querySelector('form')!
|
||
form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||
form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||
await flushPromises()
|
||
await wrapper.setProps({ target: 'second' })
|
||
finish!()
|
||
await flushPromises()
|
||
expect(onSubmit).not.toHaveBeenCalled()
|
||
})
|
||
})
|