import { afterEach, describe, expect, it, vi } from 'vitest' import { DingtalkRequestError, registerDingtalkSpace, startDingtalkSession } from './dingtalkSession' afterEach(() => vi.unstubAllGlobals()) describe('DingTalk session client', () => { it('returns the starting state immediately while the QR is being generated', async () => { const fetchMock = vi.fn().mockResolvedValue( new Response( JSON.stringify({ id: 'session-1', state: 'starting', created_at: 1, expires_at: 2, }), { status: 201 } ) ) vi.stubGlobal('fetch', fetchMock) const target = 'https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview' await expect(startDingtalkSession(target)).resolves.toMatchObject({ id: 'session-1', state: 'starting' }) expect(fetchMock).toHaveBeenCalledWith('/api/v1/dingtalk-session', expect.objectContaining({ method: 'POST' })) expect(JSON.parse(String(fetchMock.mock.calls[0][1]?.body))).toEqual({ space: target }) }) it('preserves login_required as a machine-readable error for automatic QR fallback', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( new Response(JSON.stringify({ error: 'login_required' }), { status: 409, headers: { 'Content-Type': 'application/json' }, }) ) ) const error = await registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview').then( () => null, (cause: unknown) => cause ) expect(error).toBeInstanceOf(DingtalkRequestError) expect(error).toMatchObject({ code: 'login_required', status: 409 }) }) }) describe('钉钉知识库登记的失败说明', () => { it('后端 hint 优先,其次本地文案;错误码始终带出', async () => { vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue( new Response(JSON.stringify({ error: 'space_name_conflict', hint: '已有同名来源仍在使用:先「去掉来源」' }), { status: 409, }) ) ) await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow( '已有同名来源仍在使用:先「去掉来源」' ) vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_identity_conflict' }), { status: 409 })) ) await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow( '这个登记键已指向另一个知识库空间' ) vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'space_registration_failed' }), { status: 500 })) ) await expect(registerDingtalkSpace('https://alidocs.dingtalk.com/i/spaces/x')).rejects.toThrow( '登记失败(服务端内部错误)' ) }) })