ray-template/__test__/app/route-draft-guard.spec.ts
XiaoDaiGua-Ray d67e64d48c
feat(ui): refine frontend interactions and add CURD examples
Protect route drafts and refine keyboard, responsive, and primary button behavior.

Add CURD workspace examples with tests and bilingual documentation.
2026-11-27 14:51:46 +08:00

61 lines
1.8 KiB
TypeScript

import { useRouteDraftGuard } from '@/views/route-management/use-draft-guard'
import { flushPromises, mount } from '@vue/test-utils'
import type { DialogOptions } from 'naive-ui'
import { defineComponent, h } from 'vue'
import { createMemoryHistory, createRouter, RouterView } from 'vue-router'
vi.mock('@/hooks', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
vi.mock('@/store', () => ({
useSigningGetters: () => ({ getSigningCallback: { value: { id: 'admin' } } }),
}))
it('keeps a dirty editor across a cancelled URL change and leaves after confirmation', async () => {
const warning = vi.fn((_options: DialogOptions) => ({ destroy: vi.fn() }))
vi.stubGlobal('$dialog', { warning })
const editor = defineComponent({
setup() {
useRouteDraftGuard(
() => true,
() => false,
)
return () => h('div', 'Draft editor')
},
})
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/editor', component: editor },
{ path: '/other', component: { render: () => h('div', 'Other view') } },
],
})
await router.push('/editor')
const wrapper = mount(RouterView, { global: { plugins: [router] } })
try {
const update = router.push('/editor?source=other')
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/editor')
warning.mock.lastCall?.[0].onAfterLeave?.()
await update
expect(router.currentRoute.value.fullPath).toBe('/editor')
const leave = router.push('/other')
await flushPromises()
const options = warning.mock.lastCall?.[0]
options?.onPositiveClick?.(new MouseEvent('click'))
options?.onAfterLeave?.()
await leave
expect(wrapper.text()).toBe('Other view')
expect(warning).toHaveBeenCalledTimes(2)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
}
})