test: 单元测试改为直接测试真实代码

This commit is contained in:
2026-08-03 22:21:36 +08:00
parent f71abdd000
commit 6595ed0dfc
9 changed files with 522 additions and 808 deletions
+64 -85
View File
@@ -1,112 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils' import { mount } from '@vue/test-utils'
import { createRouter, createMemoryHistory } from 'vue-router' import ElementPlus from 'element-plus'
import { reactive, ref } from 'vue' import { ElMessage } from 'element-plus'
import Login from '@/components/Login.vue'
import router from '@/router'
import { login } from '@/api/login'
// Mock API
vi.mock('@/api/login', () => ({ vi.mock('@/api/login', () => ({
login: vi.fn(), login: vi.fn(),
logout: vi.fn(), logout: vi.fn(),
})) }))
// Mock Element Plus function mountLogin() {
vi.mock('element-plus', () => ({ return mount(Login, {
ElMessage: { shallow: true,
success: vi.fn(), global: {
error: vi.fn(), plugins: [ElementPlus, router],
warning: vi.fn(), },
info: vi.fn(),
},
}))
import { login } from '@/api/login'
import { ElMessage } from 'element-plus'
function createTestRouter() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/login', component: { template: '<div/>' } },
{ path: '/welcome', component: { template: '<div/>' } },
],
}) })
} }
describe('Login.vue logic', () => { function createForm(valid = true) {
beforeEach(() => { return {
validate: (callback: (valid: boolean) => void) => callback(valid),
} as any
}
describe('Login.vue', () => {
beforeEach(async () => {
vi.clearAllMocks() vi.clearAllMocks()
localStorage.clear() localStorage.clear()
await router.push('/login')
await router.isReady()
}) })
describe('isNotEmpty validator', () => { it('isNotEmpty validator reports empty value and accepts filled value', () => {
it('calls callback with error message when value is empty', () => { const wrapper = mountLogin()
const callback = vi.fn() const callback = vi.fn()
const rule = { message: '请输入账号!' }
// isNotEmpty logic
const value = ''
if (!value) {
callback(rule.message)
} else {
callback()
}
expect(callback).toHaveBeenCalledWith('请输入账号!')
})
it('calls callback without error when value is present', () => { wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
const callback = vi.fn() expect(callback).toHaveBeenCalledWith('请输入账号!')
const rule = { message: '请输入账号!' }
const value = 'admin' wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
if (!value) { expect(callback).toHaveBeenCalledWith()
callback(rule.message)
} else {
callback()
}
expect(callback).toHaveBeenCalledWith()
})
}) })
describe('submitForm logic', () => { it('sets localStorage and navigates on successful login', async () => {
it('sets localStorage and navigates on successful login', async () => { vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any) const wrapper = mountLogin()
const router = createTestRouter() wrapper.vm.registerData.username = 'admin'
await router.push('/login') wrapper.vm.registerData.password = '123456'
await router.isReady()
// Simulate submitForm logic await wrapper.vm.submitForm(createForm(true))
const username = 'admin'
const password = '123456'
const result = await login(username, password)
if (result.code === 200) { expect(localStorage.getItem('isLoggedIn')).toBe('true')
localStorage.setItem('isLoggedIn', 'true') expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
ElMessage.success(result.message) expect(router.currentRoute.value.path).toBe('/welcome')
await router.push('/welcome') })
}
expect(localStorage.getItem('isLoggedIn')).toBe('true') it('shows error message on failed login', async () => {
expect(ElMessage.success).toHaveBeenCalledWith('登录成功') vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
expect(router.currentRoute.value.path).toBe('/welcome') const wrapper = mountLogin()
}) wrapper.vm.registerData.username = 'admin'
wrapper.vm.registerData.password = 'wrong'
it('shows error message on failed login', async () => { await wrapper.vm.submitForm(createForm(true))
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
const result = await login('admin', 'wrong') expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
if (result.code !== 200) { expect(localStorage.getItem('isLoggedIn')).toBeNull()
ElMessage.error(result.message) expect(router.currentRoute.value.path).toBe('/login')
} })
expect(ElMessage.error).toHaveBeenCalledWith('密码错误') it('does not submit again while loading', async () => {
expect(localStorage.getItem('isLoggedIn')).toBeNull() let resolveLogin!: (value: any) => void
}) vi.mocked(login).mockImplementation(
() => new Promise((resolve) => { resolveLogin = resolve }),
)
const wrapper = mountLogin()
it('does not submit when already loading', async () => { const firstSubmit = wrapper.vm.submitForm(createForm(true))
const loading = ref(true) const secondSubmit = wrapper.vm.submitForm(createForm(true))
// Simulate guard: if (!formEl || loading.value) return; await Promise.resolve()
if (loading.value) {
// Early return - no API call expect(login).toHaveBeenCalledTimes(1)
}
expect(login).not.toHaveBeenCalled() resolveLogin({ code: 200, message: '登录成功' })
}) await Promise.all([firstSubmit, secondSubmit])
expect(localStorage.getItem('isLoggedIn')).toBe('true')
}) })
}) })
+50 -84
View File
@@ -1,106 +1,72 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { computed, ref } from 'vue' import { mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import MyHead from '@/components/MyHead.vue'
import router from '@/router'
import { logout } from '@/api/login'
vi.mock('@/api/login', () => ({ vi.mock('@/api/login', () => ({
login: vi.fn(), login: vi.fn(),
logout: vi.fn().mockResolvedValue({ code: 200 }), logout: vi.fn(),
})) }))
vi.mock('element-plus', () => ({ async function mountAt(path: string) {
ElMessage: { await router.push(path)
success: vi.fn(), await router.isReady()
error: vi.fn(), return mount(MyHead, {
warning: vi.fn(), shallow: true,
info: vi.fn(), global: {
}, plugins: [ElementPlus, router],
})) },
})
}
import { logout } from '@/api/login' describe('MyHead.vue', () => {
import { ElMessage } from 'element-plus' beforeEach(async () => {
describe('MyHead.vue logic', () => {
beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
localStorage.clear() localStorage.clear()
await router.push('/login')
await router.isReady()
}) })
describe('route-based computed properties', () => { it('derives route-based computed properties from real route', async () => {
it('isLoginRoute is true when path is /login', () => { const loginWrapper = await mountAt('/login')
const routePath = ref('/login') expect(loginWrapper.vm.isLoginRoute).toBe(true)
const isLoginRoute = computed(() => routePath.value === '/login') expect(loginWrapper.vm.showBackButton).toBe(false)
expect(isLoginRoute.value).toBe(true)
})
it('isLoginRoute is false for other paths', () => { localStorage.setItem('isLoggedIn', 'true')
const routePath = ref('/welcome') const studyWrapper = await mountAt('/study')
const isLoginRoute = computed(() => routePath.value === '/login') expect(studyWrapper.vm.isLoginRoute).toBe(false)
expect(isLoginRoute.value).toBe(false) expect(studyWrapper.vm.showBackButton).toBe(true)
}) expect(studyWrapper.vm.pageTitle).toBe('学习任务')
it('showBackButton is true for non-login, non-welcome routes', () => { const welcomeWrapper = await mountAt('/welcome')
const routePath = ref('/study') expect(welcomeWrapper.vm.showBackButton).toBe(false)
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome') expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
expect(showBackButton.value).toBe(true)
})
it('showBackButton is false on welcome route', () => {
const routePath = ref('/welcome')
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
expect(showBackButton.value).toBe(false)
})
it('showBackButton is false on login route', () => {
const routePath = ref('/login')
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
expect(showBackButton.value).toBe(false)
})
it('pageTitle is derived from route meta', () => {
const meta = { title: '学习任务' }
const pageTitle = computed(() => meta?.title as string | undefined)
expect(pageTitle.value).toBe('学习任务')
})
it('pageTitle is undefined when no meta title', () => {
const meta = {}
const pageTitle = computed(() => meta?.title as string | undefined)
expect(pageTitle.value).toBeUndefined()
})
}) })
describe('handleLogout logic', () => { it('clears login state and navigates to login on logout', async () => {
it('clears login state and navigates to login', async () => { vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
localStorage.setItem('isLoggedIn', 'true') localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
// Simulate handleLogout await wrapper.vm.handleLogout()
try {
await logout()
} catch {
// Backend failure shouldn't block logout
} finally {
localStorage.removeItem('isLoggedIn')
ElMessage.success('已退出登录')
}
expect(localStorage.getItem('isLoggedIn')).toBeNull() expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录') expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
}) expect(router.currentRoute.value.path).toBe('/login')
})
it('clears login state even when API call fails', async () => { it('clears login state even when logout API fails', async () => {
vi.mocked(logout).mockRejectedValue(new Error('Network error')) vi.mocked(logout).mockRejectedValue(new Error('Network error'))
localStorage.setItem('isLoggedIn', 'true') localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
try { await wrapper.vm.handleLogout()
await logout()
} catch {
// Expected
} finally {
localStorage.removeItem('isLoggedIn')
ElMessage.success('已退出登录')
}
expect(localStorage.getItem('isLoggedIn')).toBeNull() expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录') expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
}) expect(router.currentRoute.value.path).toBe('/login')
}) })
}) })
+171 -238
View File
@@ -1,276 +1,209 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref, reactive } from 'vue' 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 {
continueSession,
endSession,
getExpectation,
getSessionDetail,
pauseSession,
startOrContinueStudySession,
} from '@/api/studySessions'
import { getFragmentsBySession } from '@/api/reportFragments'
// Mock API
vi.mock('@/api/studySessions', () => ({ vi.mock('@/api/studySessions', () => ({
continueSession: vi.fn(), continueSession: vi.fn(),
pauseSession: vi.fn(),
endSession: vi.fn(), endSession: vi.fn(),
startOrContinueStudySession: vi.fn(), getExpectation: vi.fn(),
getReportDraft: vi.fn(),
getSessionDetail: vi.fn(), getSessionDetail: vi.fn(),
getTaskFragments: vi.fn(),
getTaskReports: vi.fn(),
pauseSession: vi.fn(),
startOrContinueStudySession: vi.fn(),
upsertExpectation: vi.fn(),
})) }))
vi.mock('@/api/reportFragments', () => ({ vi.mock('@/api/reportFragments', () => ({
createFragments: vi.fn(),
getFragmentsBySession: vi.fn(), getFragmentsBySession: vi.fn(),
updateFragments: vi.fn(), updateFragments: vi.fn(),
})) }))
import { const defaultSessionData = {
continueSession, sessionNum: 'SESSION_001',
pauseSession, sessionState: 'PAUSED',
endSession, taskName: '测试任务',
startOrContinueStudySession, taskNum: 'T001',
} from '@/api/studySessions' taskId: 1,
startTime: '',
const mockedContinueSession = vi.mocked(continueSession) endTime: '',
const mockedPauseSession = vi.mocked(pauseSession) lastStartTime: '',
const mockedEndSession = vi.mocked(endSession) actualTime: 0,
const mockedStartOrContinue = vi.mocked(startOrContinueStudySession) effectiveTime: 0,
effectivenessRatio: '--',
// 模拟 StartTask.vue 中的核心状态和方法 pointerPosition: 1_500_000,
function createSessionSimulator() { systemMessage: '',
const taskInfo = reactive({
sessionNum: 'SESSION_001',
sessionState: 'ONGOING' as string,
taskName: '测试任务',
taskNum: 'T001',
startTime: '',
endTime: '',
lastStartTime: '',
actualTime: 0,
effectiveTime: 0,
effectivenessRatio: '--',
pointerPosition: 1500000,
systemMessage: '',
})
const timerRunning = ref(true)
const clear = () => {
timerRunning.value = false
}
const runCountdown = (duration: number) => {
timerRunning.value = true
}
// 从 StartTask.vue 提取的 stopTimer 逻辑
const stopTimer = async () => {
const res = await pauseSession(taskInfo.sessionNum)
if (res.code === 200) {
taskInfo.sessionState = 'PAUSED'
}
clear()
}
// 从 StartTask.vue 提取的 startTimer 逻辑
const startTimer = async () => {
if (taskInfo.sessionState === 'PAUSED') {
const res = await continueSession(taskInfo.sessionNum)
if (res.code === 200) {
// ElMessage.success("任务继续")
}
// loadTaskSession 模拟
const sessionRes = await startOrContinueStudySession(taskInfo.taskNum)
Object.assign(taskInfo, sessionRes.data)
}
const duration = taskInfo.pointerPosition || 25 * 60 * 1000
runCountdown(duration)
}
// 从 StartTask.vue 提取的 endTimer 逻辑(简化版,跳过 confirm)
const endTimer = async (content: string) => {
if (!content) return
const res = await endSession(taskInfo.sessionNum, content)
if (res.code === 200) {
if (res.message && res.message !== '请求成功') {
// ElMessage.warning(res.message)
}
}
clear()
}
return { taskInfo, timerRunning, stopTimer, startTimer, endTimer, clear }
} }
describe('StartTask.vue 暂停/继续逻辑', () => { async function mountTask() {
beforeEach(() => { 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],
},
})
await flushPromises()
return wrapper
}
describe('StartTask.vue', () => {
beforeEach(async () => {
vi.clearAllMocks() vi.clearAllMocks()
localStorage.clear()
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(ElMessageBox.confirm).mockResolvedValue('confirm')
await router.push('/login')
await router.isReady()
}) })
describe('stopTimer - 暂停', () => { it('stopTimer pauses real session state and refreshes from detail API', async () => {
it('调用 pauseSession API', async () => { vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(getSessionDetail).mockResolvedValue({
const { stopTimer } = createSessionSimulator() 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 stopTimer() await wrapper.vm.stopTimer()
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001') expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
}) expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
it('暂停成功后 sessionState 应更新为 PAUSED', async () => { expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any) expect(wrapper.vm.timerRunning).toBe(false)
const { taskInfo, stopTimer } = createSessionSimulator() wrapper.unmount()
expect(taskInfo.sessionState).toBe('ONGOING')
await stopTimer()
expect(taskInfo.sessionState).toBe('PAUSED')
})
it('暂停后 timerRunning 应为 false', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
const { timerRunning, stopTimer } = createSessionSimulator()
expect(timerRunning.value).toBe(true)
await stopTimer()
expect(timerRunning.value).toBe(false)
})
}) })
describe('startTimer - 继续', () => { it('startTimer continues a paused session and reloads session data', async () => {
it('PAUSED 状态下点击开始,应调用 continueSession API', async () => { vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any) vi.mocked(startOrContinueStudySession).mockResolvedValue({
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any) code: 200,
mockedStartOrContinue.mockResolvedValue({ data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
code: 200, } as any)
data: { const wrapper = await mountTask()
sessionNum: 'SESSION_001',
sessionState: 'ONGOING',
pointerPosition: 1500000,
},
} as any)
const { taskInfo, stopTimer, startTimer } = createSessionSimulator() // 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue
wrapper.vm.taskInfo.sessionState = 'PAUSED'
await wrapper.vm.startTimer()
// 先暂停 expect(continueSession).toHaveBeenCalledWith('SESSION_001')
await stopTimer() expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
expect(taskInfo.sessionState).toBe('PAUSED') expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
expect(wrapper.vm.timerRunning).toBe(true)
// 再开始 wrapper.unmount()
await startTimer()
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
})
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: {
sessionNum: 'SESSION_001',
sessionState: 'ONGOING',
pointerPosition: 1200000,
},
} as any)
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
await stopTimer()
await startTimer()
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
expect(taskInfo.sessionState).toBe('ONGOING')
})
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
const { taskInfo, startTimer } = createSessionSimulator()
// 直接在 ONGOING 状态调用 startTimer
expect(taskInfo.sessionState).toBe('ONGOING')
await startTimer()
expect(mockedContinueSession).not.toHaveBeenCalled()
})
it('开始后 timerRunning 应为 true', async () => {
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
await stopTimer()
expect(timerRunning.value).toBe(false)
await startTimer()
expect(timerRunning.value).toBe(true)
})
}) })
describe('endTimer - 结束会话', () => { it('startTimer does not call continue API when session is already ongoing', async () => {
it('调用 endSession API 并传递 content', async () => { const wrapper = await mountTask()
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any) wrapper.vm.taskInfo.sessionState = 'ONGOING'
const { endTimer } = createSessionSimulator()
await endTimer('学习总结内容') await wrapper.vm.startTimer()
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容') expect(continueSession).not.toHaveBeenCalled()
}) expect(wrapper.vm.timerRunning).toBe(true)
wrapper.unmount()
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
mockedEndSession.mockResolvedValue({
code: 200,
message: '本次有效学习时间不足10分钟,不计入总学习时间',
} as any)
const { endTimer } = createSessionSimulator()
const res = await endSession('SESSION_001', '内容')
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
expect(res.message).not.toBe('请求成功')
})
it('content 为空时不调用 API', async () => {
const { endTimer } = createSessionSimulator()
await endTimer('')
expect(mockedEndSession).not.toHaveBeenCalled()
})
}) })
describe('完整暂停→继续→暂停流程', () => { it('endTimer refuses empty content without calling API', async () => {
it('多次暂停/继续应正确更新状态和调用 API', async () => { const wrapper = await mountTask()
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
mockedStartOrContinue.mockResolvedValue({
code: 200,
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
} as any)
const { taskInfo, stopTimer, startTimer } = createSessionSimulator() await wrapper.vm.endTimer('')
// 初始状态 expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
expect(taskInfo.sessionState).toBe('ONGOING') expect(endSession).not.toHaveBeenCalled()
wrapper.unmount()
})
// 第一次暂停 it('endTimer ends session and navigates to study page', async () => {
await stopTimer() vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
expect(taskInfo.sessionState).toBe('PAUSED') const wrapper = await mountTask()
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
// 继续 await wrapper.vm.endTimer('学习总结内容')
await startTimer()
expect(taskInfo.sessionState).toBe('ONGOING')
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
// 第二次暂停 expect(endSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
await stopTimer() expect(ElMessage.success).toHaveBeenCalledWith('任务结束')
expect(taskInfo.sessionState).toBe('PAUSED') expect(localStorage.getItem('activeSession')).toBeNull()
expect(mockedPauseSession).toHaveBeenCalledTimes(2) expect(router.currentRoute.value.path).toBe('/study')
wrapper.unmount()
})
// 再次继续 it('endTimer shows warning message returned by backend', async () => {
await startTimer() vi.mocked(endSession).mockResolvedValue({
expect(taskInfo.sessionState).toBe('ONGOING') code: 200,
expect(mockedContinueSession).toHaveBeenCalledTimes(2) message: '本次有效学习时间不足10分钟,不计入总学习时间',
}) } as any)
const wrapper = await mountTask()
await wrapper.vm.endTimer('学习总结内容')
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()
}) })
}) })
+126 -146
View File
@@ -1,126 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref, reactive } from 'vue' import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import TaskForm from '@/components/TaskForm.vue'
import router from '@/router'
import request from '@/utils/request'
import { getTaskApplications } from '@/api/tasks'
vi.mock('element-plus', () => ({ vi.mock('@/utils/request', () => ({
ElMessage: { default: {
success: vi.fn(), get: vi.fn(),
error: vi.fn(), post: vi.fn(),
warning: vi.fn(), put: vi.fn(),
info: vi.fn(), delete: vi.fn(),
}, },
})) }))
import { ElMessage } from 'element-plus' vi.mock('@/api/tasks', () => ({
getTaskApplications: vi.fn(),
createTaskApplication: vi.fn(),
updateTaskApplication: vi.fn(),
deleteTaskApplication: vi.fn(),
}))
describe('TaskForm.vue logic', () => { vi.mock('@/utils/fetchTitle', () => ({
beforeEach(() => { getUrlTitle: vi.fn().mockResolvedValue(''),
}))
vi.mock('@/utils/markdown', () => ({
renderMarkdown: vi.fn(() => '<p>preview</p>'),
}))
async function mountAt(path: string) {
localStorage.setItem('isLoggedIn', 'true')
await router.push(path)
await router.isReady()
return mount(TaskForm, {
shallow: true,
global: {
plugins: [ElementPlus, router],
},
})
}
describe('TaskForm.vue', () => {
beforeEach(async () => {
vi.clearAllMocks() vi.clearAllMocks()
localStorage.clear()
vi.mocked(getTaskApplications).mockResolvedValue({ code: 200, data: [] })
await router.push('/login')
await router.isReady()
}) })
describe('priorityOptions', () => { it('uses real priority options and initial state', async () => {
it('contains values 0-5', () => { const wrapper = await mountAt('/add-task')
const priorityOptions = [0, 1, 2, 3, 4, 5]
expect(priorityOptions).toEqual([0, 1, 2, 3, 4, 5]) expect(wrapper.vm.priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
expect(priorityOptions.length).toBe(6) expect(wrapper.vm.priority).toEqual({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
}) })
}) })
describe('priority state management', () => { it('builds create payload from real form state and navigates to study', async () => {
it('initializes with all zeros', () => { vi.mocked(request.post).mockResolvedValue({ code: 200, message: '创建任务成功' })
const priority = reactive({ const wrapper = await mountAt('/add-task')
urgency: 0, wrapper.vm.taskName = '学习递归'
importance: 0, wrapper.vm.taskDescription = '理解递归的基本概念'
contentDifficulty: 0, wrapper.vm.materialUrl = 'https://example.com/recursion'
futureValue: 0, wrapper.vm.priority.urgency = 3
subjectivePriority: 0, wrapper.vm.priority.importance = 4
}) wrapper.vm.priority.contentDifficulty = 2
wrapper.vm.priority.futureValue = 5
wrapper.vm.priority.subjectivePriority = 3
expect(priority.urgency).toBe(0) wrapper.vm.createTask()
expect(priority.importance).toBe(0) await flushPromises()
expect(priority.contentDifficulty).toBe(0)
expect(priority.futureValue).toBe(0)
expect(priority.subjectivePriority).toBe(0)
})
it('updates individual priority fields', () => { expect(request.post).toHaveBeenCalledWith('/tasks', {
const priority = reactive({ taskName: '学习递归',
urgency: 0, taskDescription: '理解递归的基本概念',
importance: 0, materialUrl: 'https://example.com/recursion',
contentDifficulty: 0, urgency: 3,
futureValue: 0, importance: 4,
subjectivePriority: 0, contentDifficulty: 2,
}) futureValue: 5,
subjectivePriority: 3,
priority.urgency = 3
priority.importance = 5
expect(priority.urgency).toBe(3)
expect(priority.importance).toBe(5)
expect(priority.contentDifficulty).toBe(0)
}) })
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
}) })
describe('task payload construction', () => { it('loads update data from real API and maps it into form state', async () => {
it('builds correct create payload', () => { vi.mocked(request.get).mockResolvedValue({
const taskName = ref('学习递归') code: 200,
const taskDescription = ref('理解递归的基本概念') data: {
const materialURL = ref('https://example.com/recursion') taskNum: 'T001',
const priority = reactive({
urgency: 3,
importance: 4,
contentDifficulty: 2,
futureValue: 5,
subjectivePriority: 3,
})
const payload = {
taskName: taskName.value,
taskDescription: taskDescription.value,
materialURL: materialURL.value,
...priority,
}
expect(payload).toEqual({
taskName: '学习递归',
taskDescription: '理解递归的基本概念',
materialURL: 'https://example.com/recursion',
urgency: 3,
importance: 4,
contentDifficulty: 2,
futureValue: 5,
subjectivePriority: 3,
})
})
it('builds correct update payload with id', () => {
const taskId = 42
const taskName = ref('更新后的任务')
const taskDescription = ref('')
const materialURL = ref('')
const priority = reactive({
urgency: 1,
importance: 2,
contentDifficulty: 0,
futureValue: 3,
subjectivePriority: 4,
})
const payload = {
id: taskId,
taskName: taskName.value,
taskDescription: taskDescription.value,
materialURL: materialURL.value,
...priority,
}
expect(payload.id).toBe(42)
expect(payload.taskName).toBe('更新后的任务')
})
})
describe('loadTask data mapping', () => {
it('maps API response to form fields correctly', () => {
const apiData = {
taskName: '学习DP', taskName: '学习DP',
taskDescription: '动态规划', taskDescription: '动态规划',
materialUrl: 'https://example.com/dp', materialUrl: 'https://example.com/dp',
@@ -129,52 +107,54 @@ describe('TaskForm.vue logic', () => {
contentDifficulty: 3, contentDifficulty: 3,
futureValue: 4, futureValue: 4,
subjectivePriority: 2, subjectivePriority: 2,
} },
const taskName = ref('')
const taskDescription = ref('')
const materialURL = ref('')
const priority = reactive({
urgency: 0,
importance: 0,
contentDifficulty: 0,
futureValue: 0,
subjectivePriority: 0,
})
// Simulate loadTask mapping
taskName.value = apiData.taskName
taskDescription.value = apiData.taskDescription
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
priority.urgency = apiData.urgency
priority.importance = apiData.importance
priority.contentDifficulty = apiData.contentDifficulty
priority.futureValue = apiData.futureValue
priority.subjectivePriority = apiData.subjectivePriority
expect(taskName.value).toBe('学习DP')
expect(materialURL.value).toBe('https://example.com/dp')
expect(priority.urgency).toBe(4)
expect(priority.importance).toBe(5)
}) })
it('handles materialURL with camelCase variant', () => { const wrapper = await mountAt('/update-task/42')
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' } await flushPromises()
const result = apiData.materialURL || apiData.materialUrl || ''
expect(result).toBe('https://example.com/a')
})
it('falls back to empty string when no material URL', () => { expect(wrapper.vm.isUpdateMode).toBe(true)
const apiData = {} as any expect(wrapper.vm.taskNum).toBe('T001')
const result = apiData.materialURL || apiData.materialUrl || '' expect(wrapper.vm.taskName).toBe('学习DP')
expect(result).toBe('') expect(wrapper.vm.taskDescription).toBe('动态规划')
expect(wrapper.vm.materialUrl).toBe('https://example.com/dp')
expect(wrapper.vm.priority).toEqual({
urgency: 4,
importance: 5,
contentDifficulty: 3,
futureValue: 4,
subjectivePriority: 2,
}) })
}) })
describe('redirect after successful action', () => { it('builds update payload with id and navigates to study', async () => {
it('navigates to study page after create/update', () => { vi.mocked(request.get).mockResolvedValue({
const pushTarget = '/study' code: 200,
expect(pushTarget).toBe('/study') data: {
taskNum: 'T001',
taskName: '学习DP',
taskDescription: '动态规划',
materialUrl: '',
urgency: 1,
importance: 2,
contentDifficulty: 0,
futureValue: 3,
subjectivePriority: 4,
},
}) })
vi.mocked(request.put).mockResolvedValue({ code: 200, message: '更新任务成功' })
const wrapper = await mountAt('/update-task/42')
await flushPromises()
wrapper.vm.taskName = '更新后的任务'
wrapper.vm.updateTask()
await flushPromises()
expect(request.put).toHaveBeenCalledWith('/tasks/42', expect.objectContaining({
id: 42,
taskName: '更新后的任务',
}))
expect(ElMessage.success).toHaveBeenCalledWith('更新任务成功')
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
}) })
}) })
+40 -104
View File
@@ -1,155 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeEach } from 'vitest'
import { ref } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus'
import { createFragments } from '@/api/reportFragments'
const mockInfo = vi.fn() import { useStudyFragment } from '@/components/composables/fragment'
const mockSuccess = vi.fn()
const mockError = vi.fn()
const mockWarning = vi.fn()
const mockConfirm = vi.fn()
vi.mock('element-plus', () => ({
ElMessage: {
success: mockSuccess,
error: mockError,
warning: mockWarning,
info: mockInfo,
},
ElMessageBox: {
confirm: (...args: any[]) => mockConfirm(...args),
},
}))
vi.mock('@/api/reportFragments', () => ({ vi.mock('@/api/reportFragments', () => ({
createFragments: vi.fn(), createFragments: vi.fn(),
})) }))
import { createFragments } from '@/api/reportFragments' describe('useStudyFragment', () => {
describe('useStudyFragment composable logic', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
mockConfirm.mockResolvedValue('confirm') vi.mocked(ElMessageBox.confirm).mockResolvedValue('confirm')
}) })
it('openFragmentDialog resets content and shows dialog', () => { it('openFragmentDialog resets content and shows dialog', () => {
const fragmentContent = ref('old content') const { fragmentsDialogVisible, fragmentContent, openFragmentDialog } = useStudyFragment()
const fragmentsDialogVisible = ref(false) fragmentContent.value = 'old content'
fragmentContent.value = '' openFragmentDialog()
fragmentsDialogVisible.value = true
expect(fragmentContent.value).toBe('') expect(fragmentContent.value).toBe('')
expect(fragmentsDialogVisible.value).toBe(true) expect(fragmentsDialogVisible.value).toBe(true)
}) })
it('closeFragmentDialog hides dialog on confirm', async () => { it('closeFragmentDialog hides dialog after confirm', async () => {
const fragmentsDialogVisible = ref(true) const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
fragmentsDialogVisible.value = true
await mockConfirm('确定取消生成吗?', '提示', { await closeFragmentDialog()
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).then(() => {
fragmentsDialogVisible.value = false
mockInfo('已取消生成')
})
expect(fragmentsDialogVisible.value).toBe(false) expect(fragmentsDialogVisible.value).toBe(false)
expect(mockInfo).toHaveBeenCalledWith('已取消生成') expect(ElMessage.info).toHaveBeenCalledWith('已取消生成')
}) })
it('closeFragmentDialog keeps dialog open on cancel', async () => { it('closeFragmentDialog keeps dialog open when user cancels', async () => {
const fragmentsDialogVisible = ref(true) vi.mocked(ElMessageBox.confirm).mockRejectedValue('cancel')
mockConfirm.mockRejectedValue('cancel') const { fragmentsDialogVisible, closeFragmentDialog } = useStudyFragment()
fragmentsDialogVisible.value = true
try { await closeFragmentDialog()
await mockConfirm('确定取消生成吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}).then(() => {
fragmentsDialogVisible.value = false
})
} catch {
// User cancelled
}
expect(fragmentsDialogVisible.value).toBe(true) expect(fragmentsDialogVisible.value).toBe(true)
}) })
it('confirmGenerateFragment warns if content is empty', async () => { it('confirmGenerateFragment warns when content is empty', async () => {
const fragmentContent = ref(' ') const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = ' '
if (!fragmentContent.value.trim()) { const result = await confirmGenerateFragment('S001')
mockWarning('请输入学习内容!')
}
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!') expect(result).toBe(false)
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习内容!')
expect(createFragments).not.toHaveBeenCalled() expect(createFragments).not.toHaveBeenCalled()
}) })
it('confirmGenerateFragment calls API and shows success', async () => { it('confirmGenerateFragment calls API and shows success', async () => {
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any) vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
const fragmentContent = ref('学习了递归算法') const { fragmentContent, fragmentsDialogVisible, confirmGenerateFragment } = useStudyFragment()
const fragmentsDialogVisible = ref(true) fragmentContent.value = '学习了递归算法'
if (fragmentContent.value.trim()) { const result = await confirmGenerateFragment('S001')
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
const res = await createFragments('S001', fragmentContent.value)
if (res.code === 200) {
mockSuccess('学习残片生成成功!')
fragmentsDialogVisible.value = false
}
})
}
expect(result).toBe(true)
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法') expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!') expect(ElMessage.success).toHaveBeenCalledWith('学习残片生成成功!')
expect(fragmentsDialogVisible.value).toBe(false) expect(fragmentsDialogVisible.value).toBe(false)
}) })
it('confirmGenerateFragment handles API failure', async () => { it('confirmGenerateFragment handles business failure', async () => {
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any) vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
const fragmentContent = ref('学习内容') const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习内容'
if (fragmentContent.value.trim()) { const result = await confirmGenerateFragment('S001')
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
const res = await createFragments('S001', fragmentContent.value)
if (res.code !== 200) {
mockError(res.message || '生成学习残片失败')
}
})
}
expect(mockError).toHaveBeenCalledWith('生成失败') expect(result).toBe(false)
expect(ElMessage.error).toHaveBeenCalledWith('生成失败')
}) })
it('confirmGenerateFragment handles network error', async () => { it('confirmGenerateFragment handles network error', async () => {
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时')) vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
const fragmentContent = ref('学习内容') const { fragmentContent, confirmGenerateFragment } = useStudyFragment()
fragmentContent.value = '学习内容'
if (fragmentContent.value.trim()) { const result = await confirmGenerateFragment('S001')
await mockConfirm('确定要生成学习残片吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'info',
}).then(async () => {
try {
await createFragments('S001', fragmentContent.value)
} catch (error: any) {
mockError(error.message || '请求失败')
}
})
}
expect(mockError).toHaveBeenCalledWith('网络超时') expect(result).toBe(false)
expect(ElMessage.error).toHaveBeenCalledWith('网络超时')
}) })
}) })
+35 -67
View File
@@ -1,88 +1,56 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { ElMessageBox } from 'element-plus'
// We test the timer composable logic directly since it's a pure Vue composable import { useTimer } from '@/components/composables/useTimer'
// Extract the logic to test it in isolation
describe('useTimer', () => { describe('useTimer', () => {
beforeEach(() => { beforeEach(() => {
vi.useFakeTimers() vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
vi.clearAllMocks()
}) })
afterEach(() => { afterEach(() => {
vi.useRealTimers() vi.useRealTimers()
}) })
// Test the core timer logic that the composable uses it('syncDisplay writes formatted remaining time', () => {
it('formatTime converts seconds to HH:MM:SS', () => { const { timerMinutes, timerSeconds, timerIsOver, syncDisplay } = useTimer()
const formatTime = (totalSeconds: number): string => {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
}
expect(formatTime(0)).toBe('00:00:00') syncDisplay(61_000)
expect(formatTime(61)).toBe('00:01:01') expect(timerMinutes.value).toBe(1)
expect(formatTime(3661)).toBe('01:01:01') expect(timerSeconds.value).toBe(1)
expect(formatTime(59)).toBe('00:00:59') expect(timerIsOver.value).toBe(false)
expect(formatTime(3600)).toBe('01:00:00')
syncDisplay(0)
expect(timerMinutes.value).toBe(0)
expect(timerSeconds.value).toBe(0)
expect(timerIsOver.value).toBe(true)
}) })
it('formatTime handles large values', () => { it('runCountdown decreases remaining time and stops at zero', () => {
const formatTime = (totalSeconds: number): string => { const { timerMinutes, timerSeconds, timerRunning, timerIsOver, runCountdown, clear } = useTimer()
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
return [hours, minutes, seconds].map(v => String(v).padStart(2, '0')).join(':')
}
expect(formatTime(86399)).toBe('23:59:59') runCountdown(3000)
expect(formatTime(100000)).toBe('27:46:40') vi.advanceTimersByTime(1000)
expect(timerMinutes.value).toBe(0)
expect(timerSeconds.value).toBe(2)
expect(timerRunning.value).toBe(true)
vi.advanceTimersByTime(2000)
expect(timerSeconds.value).toBe(0)
expect(timerRunning.value).toBe(false)
expect(timerIsOver.value).toBe(true)
clear()
}) })
it('timer increments elapsedSeconds over time', () => { it('notifies when countdown completes', () => {
let elapsed = 0 const { runCountdown, clear } = useTimer()
const interval = setInterval(() => {
elapsed++
}, 1000)
vi.advanceTimersByTime(3000) runCountdown(1000)
expect(elapsed).toBe(3) vi.advanceTimersByTime(1000)
vi.advanceTimersByTime(2000) expect(ElMessageBox.alert).toHaveBeenCalled()
expect(elapsed).toBe(5) clear()
clearInterval(interval)
})
it('timer can be paused and resumed', () => {
let elapsed = 0
let intervalId: ReturnType<typeof setInterval> | null = null
const start = () => {
if (!intervalId) {
intervalId = setInterval(() => { elapsed++ }, 1000)
}
}
const pause = () => {
if (intervalId) {
clearInterval(intervalId)
intervalId = null
}
}
start()
vi.advanceTimersByTime(2000)
expect(elapsed).toBe(2)
pause()
vi.advanceTimersByTime(3000)
expect(elapsed).toBe(2) // Should not change while paused
start()
vi.advanceTimersByTime(2000)
expect(elapsed).toBe(4)
pause()
}) })
}) })
+9 -63
View File
@@ -1,90 +1,36 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, beforeEach } from 'vitest'
import { createRouter, createMemoryHistory } from 'vue-router' import router from '@/router'
// We test the guard logic by importing the router and simulating navigation
// The router in src/router/index.ts uses createWebHistory which requires DOM,
// so we'll test the guard logic by recreating the key patterns.
describe('route guards', () => { describe('route guards', () => {
beforeEach(() => { beforeEach(async () => {
localStorage.clear() localStorage.clear()
vi.restoreAllMocks() await router.push('/login')
await router.isReady()
}) })
function buildRouter() {
return createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/login', component: { template: '<div/>' }, meta: { requiresAuth: false } },
{ path: '/welcome', component: { template: '<div/>' }, meta: { requiresAuth: true } },
{ path: '/study', component: { template: '<div/>' }, meta: { requiresAuth: true } },
{ path: '/', redirect: '/login' },
],
})
}
it('redirects unauthenticated user from protected route to /login', async () => { it('redirects unauthenticated user from protected route to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/welcome') await router.push('/welcome')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login') expect(router.currentRoute.value.path).toBe('/login')
}) })
it('allows authenticated user to access protected route', async () => { it('allows authenticated user to access protected route', async () => {
localStorage.setItem('isLoggedIn', 'true') localStorage.setItem('isLoggedIn', 'true')
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/welcome') await router.push('/welcome')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/welcome') expect(router.currentRoute.value.path).toBe('/welcome')
}) })
it('allows unauthenticated access to /login', async () => { it('allows unauthenticated access to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/login') await router.push('/login')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login') expect(router.currentRoute.value.path).toBe('/login')
}) })
it('root path redirects to /login', async () => { it('root path redirects to /login', async () => {
const router = buildRouter()
router.beforeEach((to, _from, next) => {
const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
if (to.meta.requiresAuth && !isLoggedIn) {
next({ path: '/login' })
} else {
next()
}
})
await router.push('/') await router.push('/')
await router.isReady()
expect(router.currentRoute.value.path).toBe('/login') expect(router.currentRoute.value.path).toBe('/login')
}) })
}) })
+27 -12
View File
@@ -1,14 +1,29 @@
import { vi } from 'vitest' import { vi } from 'vitest'
// Mock Element Plus components globally // 只 mock Element Plus 的服务,组件保持真实实现,方便测试里挂载真实组件
vi.mock('element-plus', () => ({ vi.mock('element-plus', async (importOriginal) => {
ElMessage: { const actual = await importOriginal<typeof import('element-plus')>()
success: vi.fn(), return {
error: vi.fn(), ...actual,
warning: vi.fn(), ElMessage: {
info: vi.fn(), success: vi.fn(),
}, error: vi.fn(),
ElMessageBox: { warning: vi.fn(),
confirm: vi.fn().mockResolvedValue('confirm'), info: vi.fn(),
}, },
})) ElMessageBox: {
confirm: vi.fn().mockResolvedValue('confirm'),
alert: vi.fn().mockResolvedValue(undefined),
},
}
})
// jsdom 没有 Audio,组件和 useTimer 需要用到
class MockAudio {
loop = false
currentTime = 0
play = vi.fn().mockResolvedValue(undefined)
pause = vi.fn()
}
vi.stubGlobal('Audio', MockAudio)
-9
View File
@@ -22,15 +22,6 @@ vi.mock('axios', () => ({
}, },
})) }))
vi.mock('element-plus', () => ({
ElMessage: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
},
}))
import request from '@/utils/request' import request from '@/utils/request'
describe('request utility', () => { describe('request utility', () => {