import { describe, it, expect, vi, beforeEach } from 'vitest' import { flushPromises, mount } from '@vue/test-utils' import ElementPlus from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus' import { createMemoryHistory, createRouter } from 'vue-router' import StartTask from '@/components/StartTask.vue' import router from '@/router' import { abortSession, continueSession, endSession, getActiveSession, getExpectation, getSessionDetail, pauseSession, startOrContinueStudySession, } from '@/api/studySessions' import { getFragmentsBySession } from '@/api/reportFragments' import { getTaskReview } from '@/api/review' import { getMarkersBatch } from '@/api/markers' import { getRecall, listRecalls } from '@/api/recalls' vi.mock('@/api/studySessions', () => ({ abortSession: vi.fn(), continueSession: vi.fn(), endSession: vi.fn(), getActiveSession: vi.fn(), getExpectation: vi.fn(), getSessionDetail: vi.fn(), getTaskFragments: vi.fn(), getTaskReports: vi.fn(), pauseSession: vi.fn(), startOrContinueStudySession: vi.fn(), upsertExpectation: vi.fn(), })) vi.mock('@/api/aiTasks', async (importOriginal) => { const actual = await importOriginal() return { ...actual, submitAiTask: vi.fn(), getAiTask: vi.fn(), getLatestAiTask: vi.fn(), } }) vi.mock('@/api/reportFragments', () => ({ createFragments: vi.fn(), getFragmentsBySession: vi.fn(), updateFragments: vi.fn(), })) vi.mock('@/api/review', () => ({ getTaskReview: vi.fn(), })) vi.mock('@/api/markers', () => ({ getMarkersBatch: vi.fn(), })) vi.mock('@/api/recalls', () => ({ getRecall: vi.fn(), listRecalls: vi.fn(), })) const defaultSessionData = { sessionNum: 'SESSION_001', sessionState: 'PAUSED', taskName: '测试任务', taskNum: 'T001', taskId: 1, startTime: '', endTime: '', lastStartTime: '', actualTime: 0, effectiveTime: 0, effectivenessRatio: '--', pointerPosition: 1_500_000, systemMessage: '', } async function mountTask(extraStubs: Record = {}) { localStorage.setItem('isLoggedIn', 'true') const testRouter = createRouter({ history: createMemoryHistory(), routes: [ { path: '/start-task/:taskNum', component: StartTask, meta: { requiresAuth: true, title: '学习会话' }, }, ], }) await testRouter.push('/start-task/T001') await testRouter.isReady() const wrapper = mount(StartTask, { shallow: true, global: { plugins: [ElementPlus, testRouter], stubs: extraStubs, }, }) await flushPromises() return wrapper } describe('StartTask.vue', () => { beforeEach(async () => { vi.clearAllMocks() localStorage.clear() vi.mocked(getActiveSession).mockResolvedValue({ code: 200, data: null } as any) vi.mocked(startOrContinueStudySession).mockResolvedValue({ code: 200, data: defaultSessionData } as any) vi.mocked(getExpectation).mockResolvedValue({ code: 200, data: { description: '本次学习预期' } } as any) vi.mocked(getFragmentsBySession).mockResolvedValue({ code: 200, data: [] } as any) vi.mocked(getTaskReview).mockResolvedValue({ code: 200, data: [] } as any) vi.mocked(getMarkersBatch).mockResolvedValue({ code: 200, data: {} } as any) vi.mocked(listRecalls).mockResolvedValue({ code: 200, data: { current: 1, size: 100, total: 0, records: [] }, } as any) vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm') await router.push('/login') await router.isReady() }) it('stopTimer pauses real session state and refreshes from detail API', async () => { vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(getSessionDetail).mockResolvedValue({ code: 200, data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20, effectivenessRatio: 0.8, pointerPosition: 1_200_000, }, } as any) const wrapper = await mountTask() wrapper.vm.taskInfo.sessionState = 'ONGOING' wrapper.vm.timerRunning = true await wrapper.vm.stopTimer() expect(pauseSession).toHaveBeenCalledWith('SESSION_001') expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED') expect(wrapper.vm.taskInfo.actualTime).toBe(10) expect(wrapper.vm.taskInfo.effectiveTime).toBe(20) // 后端返回 0.8,UI 统一按百分比展示 expect(wrapper.vm.taskInfo.effectivenessRatio).toBe('80.0%') expect(wrapper.vm.timerRunning).toBe(false) wrapper.unmount() }) it('startTimer continues a paused session and reloads session data', async () => { vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(startOrContinueStudySession).mockResolvedValue({ code: 200, data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 }, } as any) const wrapper = await mountTask() // 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue wrapper.vm.taskInfo.sessionState = 'PAUSED' await wrapper.vm.startTimer() expect(continueSession).toHaveBeenCalledWith('SESSION_001') expect(startOrContinueStudySession).toHaveBeenCalledWith('T001') expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING') expect(wrapper.vm.timerRunning).toBe(true) wrapper.unmount() }) it('startTimer does not call continue API when session is already ongoing', async () => { const wrapper = await mountTask() wrapper.vm.taskInfo.sessionState = 'ONGOING' await wrapper.vm.startTimer() expect(continueSession).not.toHaveBeenCalled() expect(wrapper.vm.timerRunning).toBe(true) wrapper.unmount() }) it('redirects to another active task only after the user picks 前往继续', async () => { vi.mocked(getActiveSession).mockResolvedValue({ code: 200, data: { taskNum: 'T002', taskName: '其他任务', sessionNum: 'S002' }, } as any) const pushSpy = vi.spyOn(router, 'push').mockResolvedValue() const wrapper = await mountTask() await flushPromises() // 会话-05:拦截弹窗出现,用户未选出口前不开始、也不跳转 expect(wrapper.vm.conflictSession?.taskNum).toBe('T002') expect(startOrContinueStudySession).not.toHaveBeenCalled() expect(pushSpy).not.toHaveBeenCalled() // 执行「前往继续」出口 wrapper.vm.resolveConflict('continue') await flushPromises() expect(pushSpy).toHaveBeenCalledWith('/start-task/T002') expect(startOrContinueStudySession).not.toHaveBeenCalled() pushSpy.mockRestore() wrapper.unmount() }) it('endTimer refuses an empty three-section report without calling API', async () => { const wrapper = await mountTask() await wrapper.vm.endTimer({ sessionSummary: '', expectationVerdict: '', freeSummary: ' ' }) expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容') expect(endSession).not.toHaveBeenCalled() wrapper.unmount() }) it('endTimer submits all three sections and navigates to study page', async () => { vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) const wrapper = await mountTask() const sections = { sessionSummary: '摘要', expectationVerdict: '判断', freeSummary: '自由总结' } await wrapper.vm.endTimer(sections) expect(endSession).toHaveBeenCalledWith('SESSION_001', sections) expect(ElMessage.success).toHaveBeenCalledWith('任务结束') expect(localStorage.getItem('activeSession')).toBeNull() expect(router.currentRoute.value.path).toBe('/study') wrapper.unmount() }) it('endTimer shows warning message returned by backend', async () => { vi.mocked(endSession).mockResolvedValue({ code: 200, message: '本次有效学习时间不足10分钟,不计入总学习时间', } as any) const wrapper = await mountTask() await wrapper.vm.endTimer({ sessionSummary: '摘要', expectationVerdict: '', freeSummary: '' }) expect(ElMessage.warning).toHaveBeenCalledWith('本次有效学习时间不足10分钟,不计入总学习时间') wrapper.unmount() }) it('supports a full pause -> continue -> pause flow', async () => { vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(getSessionDetail).mockResolvedValue({ code: 200, data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 }, } as any) vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(startOrContinueStudySession).mockResolvedValue({ code: 200, data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 }, } as any) const wrapper = await mountTask() wrapper.vm.taskInfo.sessionState = 'ONGOING' wrapper.vm.timerRunning = true await wrapper.vm.stopTimer() expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED') expect(pauseSession).toHaveBeenCalledTimes(1) await wrapper.vm.startTimer() expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING') expect(continueSession).toHaveBeenCalledTimes(1) await wrapper.vm.stopTimer() expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED') expect(pauseSession).toHaveBeenCalledTimes(2) wrapper.unmount() }) it('confirmAbort aborts session with correct phrase and navigates to study page', async () => { vi.mocked(abortSession).mockResolvedValue({ code: 200, message: '请求成功' } as any) const wrapper = await mountTask() wrapper.vm.abortConfirmation = '我误操作导致开启了本次学习' await wrapper.vm.confirmAbort() expect(abortSession).toHaveBeenCalledWith('SESSION_001', '我误操作导致开启了本次学习') expect(ElMessage.success).toHaveBeenCalledWith('本次学习已关闭,未产生任何数据') expect(localStorage.getItem('activeSession')).toBeNull() expect(router.currentRoute.value.path).toBe('/study') wrapper.unmount() }) it('confirmAbort refuses wrong phrase without calling API', async () => { const wrapper = await mountTask() wrapper.vm.abortConfirmation = '不是确认语' await wrapper.vm.confirmAbort() expect(ElMessage.warning).toHaveBeenCalledWith('确认语输入不正确,请重新输入') expect(abortSession).not.toHaveBeenCalled() wrapper.unmount() }) it('confirmAbort shows backend message when session has fragments and stays on page', async () => { vi.mocked(abortSession).mockRejectedValue({ code: 400, message: '这次学习已经产生了知识碎片,不能按误操作结束了哦', } as any) const wrapper = await mountTask() wrapper.vm.abortConfirmation = '我误操作导致开启了本次学习' await wrapper.vm.confirmAbort() expect(ElMessage.error).toHaveBeenCalledWith('这次学习已经产生了知识碎片,不能按误操作结束了哦') expect(router.currentRoute.value.path).not.toBe('/study') wrapper.unmount() }) it('相关导图默认收起,展开前不读取', async () => { const wrapper = await mountTask() expect(wrapper.find('.mindmap-toggle').exists()).toBe(true) expect(wrapper.find('.mindmap-body').exists()).toBe(false) expect(getTaskReview).not.toHaveBeenCalled() expect(getMarkersBatch).not.toHaveBeenCalled() expect(listRecalls).not.toHaveBeenCalled() wrapper.unmount() }) it('展开后只列出与任务碎片标签有交集的回忆,并标出命中标签', async () => { vi.mocked(getTaskReview).mockResolvedValue({ code: 200, data: [ { id: 11, sourceType: 'FRAGMENT', taskNum: 'T001', taskName: '测试任务' }, { id: 12, sourceType: 'FRAGMENT', taskNum: 'T001', taskName: '测试任务' }, { id: 99, sourceType: 'REPORT', taskNum: 'T001', taskName: '测试任务' }, ], } as any) vi.mocked(getMarkersBatch).mockResolvedValue({ code: 200, data: { '11': [ { kind: 'USER', markerName: '线性代数' }, { kind: 'SYSTEM', markerName: '来源' }, ], '12': [{ kind: 'USER', markerName: '测试任务' }], }, } as any) vi.mocked(listRecalls).mockResolvedValue({ code: 200, data: { current: 1, size: 100, total: 2, records: [ { recallNum: 'R1', status: 'ENDED', scope: { type: 'TAG', tags: ['线性代数', '概率论'], displayName: '线性代数 / 概率论', }, updatedAt: '2026-11-20T10:00:00', }, { recallNum: 'R2', status: 'ENDED', scope: { type: 'TAG', tags: ['英语'], displayName: '英语' }, updatedAt: '2026-11-19T10:00:00', }, ], }, } as any) const wrapper = await mountTask() await wrapper.find('.mindmap-toggle').trigger('click') await flushPromises() expect(getMarkersBatch).toHaveBeenCalledWith('FRAGMENT', ['11', '12']) expect(listRecalls).toHaveBeenCalledWith( { scopeType: 'TAG', pageNum: 1, pageSize: 100 }, { silent: true }, ) const rows = wrapper.findAll('.related-map-row') expect(rows).toHaveLength(1) expect(rows[0].text()).toContain('线性代数 / 概率论') expect(rows[0].text()).toContain('命中标签:线性代数') expect(rows[0].text()).not.toContain('英语') wrapper.unmount() }) it('任务没有带用户标签的碎片时,展开只给一行空态', async () => { vi.mocked(getTaskReview).mockResolvedValue({ code: 200, data: [{ id: 11, sourceType: 'FRAGMENT', taskNum: 'T001' }], } as any) vi.mocked(getMarkersBatch).mockResolvedValue({ code: 200, data: { '11': [] } } as any) const wrapper = await mountTask() await wrapper.find('.mindmap-toggle').trigger('click') await flushPromises() expect(listRecalls).not.toHaveBeenCalled() expect(wrapper.text()).toContain('这个任务的知识碎片标签还没有对应的回忆导图') wrapper.unmount() }) it('点击一条回忆后只读渲染完整导图', async () => { vi.mocked(getTaskReview).mockResolvedValue({ code: 200, data: [{ id: 11, sourceType: 'FRAGMENT', taskNum: 'T001' }], } as any) vi.mocked(getMarkersBatch).mockResolvedValue({ code: 200, data: { '11': [{ kind: 'USER', markerName: '线性代数' }] }, } as any) vi.mocked(listRecalls).mockResolvedValue({ code: 200, data: { current: 1, size: 100, total: 1, records: [ { recallNum: 'R1', status: 'ENDED', scope: { type: 'TAG', tags: ['线性代数'], displayName: '线性代数' }, updatedAt: '2026-11-20T10:00:00', }, ], }, } as any) vi.mocked(getRecall).mockResolvedValue({ code: 200, data: { recallNum: 'R1', expression: { schemaVersion: 1, root: { id: 'root', title: '根主题', notes: '', provenance: [], children: [] }, }, }, } as any) const wrapper = await mountTask({ MindMapViewer: { name: 'MindMapViewer', props: { tree: Object, recallContent: Boolean, height: String }, template: '
', }, }) await wrapper.find('.mindmap-toggle').trigger('click') await flushPromises() await wrapper.find('.related-map-row').trigger('click') await flushPromises() expect(getRecall).toHaveBeenCalledWith('R1') const viewer = wrapper.findComponent({ name: 'MindMapViewer' }) expect(viewer.exists()).toBe(true) expect(viewer.props('recallContent')).toBe(true) expect((viewer.props('tree') as any)?.title).toBe('根主题') expect(viewer.props('editable')).toBeUndefined() wrapper.unmount() }) it('读取失败给出原因并能重试', async () => { vi.mocked(getTaskReview).mockRejectedValueOnce(new Error('network')) const wrapper = await mountTask() await wrapper.find('.mindmap-toggle').trigger('click') await flushPromises() expect(wrapper.text()).toContain('相关导图读取失败') vi.mocked(getTaskReview).mockResolvedValue({ code: 200, data: [] } as any) await wrapper.find('.mindmap-retry').trigger('click') await flushPromises() expect(wrapper.text()).toContain('这个任务的知识碎片标签还没有对应的回忆导图') wrapper.unmount() }) })