Files
management/Management/tests/component-step-only.test.ts

238 lines
8.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { act, createElement } from 'react'
import { createRoot } from 'react-dom/client'
import { createMemoryRouter, RouterProvider } from 'react-router-dom'
import { afterEach, expect, it, vi } from 'vitest'
import { Group } from 'three'
import { ComponentUploadPage } from '@/pages/ComponentUploadPage'
import { Notifications } from '@/app/Notifications'
import { componentGateway } from '@/application/component-gateway'
import { ComponentUploadSession } from '@/application/component-upload'
import {
componentForm,
emptyPartInformation,
type ComponentDetail,
} from '@/domain/component-catalog'
vi.mock('@/infrastructure/step-loader', () => ({
loadLocalStepModel: vi.fn(async () => ({ root: new Group(), faceCount: 1, dispose: vi.fn() })),
}))
vi.mock('@/components/ModelPreview', () => ({
ModelPreview: () => createElement('div', {}, '模型预览'),
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
const step = () => new File(['test STEP data'], 'part.step')
const detail = (): ComponentDetail => ({
...componentForm(emptyPartInformation()),
id: 123,
componentCode: 'CW-123',
status: 'ENABLED',
stepObjectKey: 'step/part.step',
stepUrl: '/admin-api/component-assets/step/part.step',
version: 1,
createdAt: '',
updatedAt: '',
urdfMainObjectKey: null,
urdfPrefix: null,
urdfFiles: null,
})
async function renderEditor(path: string) {
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
const host = document.createElement('div')
document.body.append(host)
const root = createRoot(host)
const router = createMemoryRouter(
[
{ path: '/components/new', element: createElement(ComponentUploadPage) },
{ path: '/components/:id', element: createElement(ComponentUploadPage) },
{ path: '/components', element: createElement('div', {}, '组件已保存') },
],
{ initialEntries: [path] },
)
await act(async () =>
root.render(
createElement(Notifications, { children: createElement(RouterProvider, { router }) }),
),
)
return {
host,
async close() {
await act(async () => root.unmount())
router.dispose()
host.remove()
},
}
}
async function submit(host: HTMLElement) {
await act(async () =>
host
.querySelector('form')!
.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })),
)
}
it('requires STEP but creates a component with only STEP and all optional fields blank', async () => {
const upload = vi
.spyOn(ComponentUploadSession.prototype, 'upload')
.mockResolvedValue({ uploadSessionToken: 'test', stepObjectKey: 'step/part.step' })
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(detail())
const view = await renderEditor('/components/new')
try {
expect(view.host.querySelectorAll('.field b')).toHaveLength(0)
expect([...view.host.querySelectorAll('.source-required')].map((e) => e.textContent)).toEqual([
'必填',
'选填',
])
await submit(view.host)
expect(view.host.textContent).toContain('请先上传一个 STEP 文件')
expect(save).not.toHaveBeenCalled()
const input = view.host.querySelector<HTMLInputElement>(
'input[type=file][accept=".step,.stp"]',
)!
const selected = step()
Object.defineProperty(input, 'files', { value: [selected], configurable: true })
await act(async () => input.dispatchEvent(new Event('change', { bubbles: true })))
await submit(view.host)
expect(upload.mock.calls[0].slice(0, 3)).toEqual([selected, [], undefined])
expect(save.mock.calls[0][0]).toMatchObject({
componentName: '',
category: '',
massKg: null,
degreesOfFreedom: null,
torqueNm: null,
urdfInfo: null,
})
expect(save.mock.calls[0][1]).not.toHaveProperty('urdfObjectKeys')
expect(view.host.textContent).toContain('组件已保存')
} finally {
await view.close()
}
})
it('opens and saves an existing STEP-only component without downloading nonexistent URDF', async () => {
const existing = detail()
vi.spyOn(componentGateway, 'detail').mockResolvedValue(existing)
vi.spyOn(componentGateway, 'step').mockResolvedValue(step())
const urdf = vi.spyOn(componentGateway, 'urdf')
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({})
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(existing)
const view = await renderEditor('/components/123')
try {
expect(urdf).not.toHaveBeenCalled()
const tabs = [
...view.host.querySelectorAll<HTMLButtonElement>('[aria-label="模型类型"] button'),
]
expect(tabs[0].getAttribute('aria-selected')).toBe('true')
expect(tabs[1].disabled).toBe(true)
expect(view.host.textContent).not.toContain('null 个文件')
await submit(view.host)
expect(save.mock.calls[0][2]).toEqual(existing)
expect(view.host.textContent).toContain('组件已保存')
} finally {
await view.close()
}
})
it('submits the new STEP-only filename category without requiring URDF or optional fields', async () => {
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({
uploadSessionToken: 'test',
stepObjectKey: 'step/足_L_轻量足.step',
})
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(detail())
const view = await renderEditor('/components/new')
try {
const input = view.host.querySelector<HTMLInputElement>(
'input[type=file][accept=".step,.stp"]',
)!
Object.defineProperty(input, 'files', {
value: [new File(['test STEP data'], '足_L_轻量足.step')],
configurable: true,
})
await act(async () => input.dispatchEvent(new Event('change', { bubbles: true })))
expect(view.host.textContent).toContain('足 · 左,由模型文件名自动识别')
await submit(view.host)
expect(save.mock.calls[0][0]).toMatchObject({
category: 'LEG_L',
componentName: '',
urdfInfo: null,
basicFields: [
{ name: 'partType', value: 'LEG' },
{ name: 'partSide', value: 'L' },
],
})
} finally {
await view.close()
}
})
it('restores rotationAxis on edit and submits null when the user clears it', async () => {
const existing = { ...detail(), rotationAxis: 'z' as const }
vi.spyOn(componentGateway, 'detail').mockResolvedValue(existing)
vi.spyOn(componentGateway, 'step').mockResolvedValue(step())
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({})
const save = vi
.spyOn(componentGateway, 'save')
.mockResolvedValue({ ...existing, rotationAxis: null })
const view = await renderEditor('/components/123')
try {
const select = view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!
expect(select.value).toBe('z')
await act(async () => {
select.value = ''
select.dispatchEvent(new Event('change', { bubbles: true }))
})
await submit(view.host)
expect(save.mock.calls[0][0].rotationAxis).toBeNull()
expect(view.host.textContent).toContain('组件已保存')
} finally {
await view.close()
}
})
it('reports a backend that drops rotationAxis instead of falsely claiming the axis was saved', async () => {
const existing = detail()
vi.spyOn(componentGateway, 'detail').mockResolvedValue(existing)
vi.spyOn(componentGateway, 'step').mockResolvedValue(step())
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({})
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(existing)
const view = await renderEditor('/components/123')
try {
const select = view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!
await act(async () => {
select.value = 'z'
select.dispatchEvent(new Event('change', { bubbles: true }))
})
await submit(view.host)
expect(save.mock.calls[0][0].rotationAxis).toBe('Z')
expect(view.host.textContent).toContain('后端未返回一致的 旋转轴(rotationAxis)')
expect(view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!.value).toBe(
'z',
)
} finally {
await view.close()
}
})
it('submits uppercase Z and accepts the same uppercase axis returned by the backend', async () => {
const existing = { ...detail(), rotationAxis: 'Z' as const }
vi.spyOn(componentGateway, 'detail').mockResolvedValue(existing)
vi.spyOn(componentGateway, 'step').mockResolvedValue(step())
vi.spyOn(ComponentUploadSession.prototype, 'upload').mockResolvedValue({})
const save = vi.spyOn(componentGateway, 'save').mockResolvedValue(existing)
const view = await renderEditor('/components/123')
try {
expect(view.host.querySelector<HTMLSelectElement>('select[aria-label="旋转轴"]')!.value).toBe(
'z',
)
await submit(view.host)
expect(save.mock.calls[0][0].rotationAxis).toBe('Z')
expect(view.host.textContent).toContain('组件已保存')
expect(view.host.textContent).not.toContain('后端未返回一致的')
} finally {
await view.close()
}
})