test: 单元测试改为直接测试真实代码
This commit is contained in:
@@ -1,87 +1,57 @@
|
|||||||
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()
|
||||||
})
|
|
||||||
|
|
||||||
describe('isNotEmpty validator', () => {
|
|
||||||
it('calls callback with error message when value is empty', () => {
|
|
||||||
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', () => {
|
|
||||||
const callback = vi.fn()
|
|
||||||
const rule = { message: '请输入账号!' }
|
|
||||||
const value = 'admin'
|
|
||||||
if (!value) {
|
|
||||||
callback(rule.message)
|
|
||||||
} else {
|
|
||||||
callback()
|
|
||||||
}
|
|
||||||
expect(callback).toHaveBeenCalledWith()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('submitForm logic', () => {
|
|
||||||
it('sets localStorage and navigates on successful login', async () => {
|
|
||||||
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
|
||||||
const router = createTestRouter()
|
|
||||||
await router.push('/login')
|
await router.push('/login')
|
||||||
await router.isReady()
|
await router.isReady()
|
||||||
|
})
|
||||||
|
|
||||||
// Simulate submitForm logic
|
it('isNotEmpty validator reports empty value and accepts filled value', () => {
|
||||||
const username = 'admin'
|
const wrapper = mountLogin()
|
||||||
const password = '123456'
|
const callback = vi.fn()
|
||||||
const result = await login(username, password)
|
|
||||||
|
|
||||||
if (result.code === 200) {
|
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, '', callback)
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
expect(callback).toHaveBeenCalledWith('请输入账号!')
|
||||||
ElMessage.success(result.message)
|
|
||||||
await router.push('/welcome')
|
wrapper.vm.isNotEmpty({ message: '请输入账号!' } as any, 'admin', callback)
|
||||||
}
|
expect(callback).toHaveBeenCalledWith()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('sets localStorage and navigates on successful login', async () => {
|
||||||
|
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
|
||||||
|
const wrapper = mountLogin()
|
||||||
|
wrapper.vm.registerData.username = 'admin'
|
||||||
|
wrapper.vm.registerData.password = '123456'
|
||||||
|
|
||||||
|
await wrapper.vm.submitForm(createForm(true))
|
||||||
|
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||||
@@ -90,23 +60,32 @@ describe('Login.vue logic', () => {
|
|||||||
|
|
||||||
it('shows error message on failed login', async () => {
|
it('shows error message on failed login', async () => {
|
||||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||||
|
const wrapper = mountLogin()
|
||||||
|
wrapper.vm.registerData.username = 'admin'
|
||||||
|
wrapper.vm.registerData.password = 'wrong'
|
||||||
|
|
||||||
const result = await login('admin', 'wrong')
|
await wrapper.vm.submitForm(createForm(true))
|
||||||
if (result.code !== 200) {
|
|
||||||
ElMessage.error(result.message)
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||||
|
expect(router.currentRoute.value.path).toBe('/login')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('does not submit when already loading', async () => {
|
it('does not submit again while loading', async () => {
|
||||||
const loading = ref(true)
|
let resolveLogin!: (value: any) => void
|
||||||
// Simulate guard: if (!formEl || loading.value) return;
|
vi.mocked(login).mockImplementation(
|
||||||
if (loading.value) {
|
() => new Promise((resolve) => { resolveLogin = resolve }),
|
||||||
// Early return - no API call
|
)
|
||||||
}
|
const wrapper = mountLogin()
|
||||||
expect(login).not.toHaveBeenCalled()
|
|
||||||
})
|
const firstSubmit = wrapper.vm.submitForm(createForm(true))
|
||||||
|
const secondSubmit = wrapper.vm.submitForm(createForm(true))
|
||||||
|
await Promise.resolve()
|
||||||
|
|
||||||
|
expect(login).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
|
resolveLogin({ code: 200, message: '登录成功' })
|
||||||
|
await Promise.all([firstSubmit, secondSubmit])
|
||||||
|
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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', () => {
|
|
||||||
const routePath = ref('/welcome')
|
|
||||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
|
||||||
expect(isLoginRoute.value).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
it('showBackButton is true for non-login, non-welcome routes', () => {
|
|
||||||
const routePath = ref('/study')
|
|
||||||
const showBackButton = computed(() => routePath.value !== '/login' && routePath.value !== '/welcome')
|
|
||||||
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', async () => {
|
|
||||||
localStorage.setItem('isLoggedIn', 'true')
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
|
const studyWrapper = await mountAt('/study')
|
||||||
|
expect(studyWrapper.vm.isLoginRoute).toBe(false)
|
||||||
|
expect(studyWrapper.vm.showBackButton).toBe(true)
|
||||||
|
expect(studyWrapper.vm.pageTitle).toBe('学习任务')
|
||||||
|
|
||||||
// Simulate handleLogout
|
const welcomeWrapper = await mountAt('/welcome')
|
||||||
try {
|
expect(welcomeWrapper.vm.showBackButton).toBe(false)
|
||||||
await logout()
|
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
|
||||||
} catch {
|
})
|
||||||
// Backend failure shouldn't block logout
|
|
||||||
} finally {
|
it('clears login state and navigates to login on logout', async () => {
|
||||||
localStorage.removeItem('isLoggedIn')
|
vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
|
||||||
ElMessage.success('已退出登录')
|
localStorage.setItem('isLoggedIn', 'true')
|
||||||
}
|
const wrapper = await mountAt('/study')
|
||||||
|
|
||||||
|
await wrapper.vm.handleLogout()
|
||||||
|
|
||||||
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')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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,
|
|
||||||
pauseSession,
|
|
||||||
endSession,
|
|
||||||
startOrContinueStudySession,
|
|
||||||
} from '@/api/studySessions'
|
|
||||||
|
|
||||||
const mockedContinueSession = vi.mocked(continueSession)
|
|
||||||
const mockedPauseSession = vi.mocked(pauseSession)
|
|
||||||
const mockedEndSession = vi.mocked(endSession)
|
|
||||||
const mockedStartOrContinue = vi.mocked(startOrContinueStudySession)
|
|
||||||
|
|
||||||
// 模拟 StartTask.vue 中的核心状态和方法
|
|
||||||
function createSessionSimulator() {
|
|
||||||
const taskInfo = reactive({
|
|
||||||
sessionNum: 'SESSION_001',
|
sessionNum: 'SESSION_001',
|
||||||
sessionState: 'ONGOING' as string,
|
sessionState: 'PAUSED',
|
||||||
taskName: '测试任务',
|
taskName: '测试任务',
|
||||||
taskNum: 'T001',
|
taskNum: 'T001',
|
||||||
|
taskId: 1,
|
||||||
startTime: '',
|
startTime: '',
|
||||||
endTime: '',
|
endTime: '',
|
||||||
lastStartTime: '',
|
lastStartTime: '',
|
||||||
actualTime: 0,
|
actualTime: 0,
|
||||||
effectiveTime: 0,
|
effectiveTime: 0,
|
||||||
effectivenessRatio: '--',
|
effectivenessRatio: '--',
|
||||||
pointerPosition: 1500000,
|
pointerPosition: 1_500_000,
|
||||||
systemMessage: '',
|
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()
|
|
||||||
|
|
||||||
await stopTimer()
|
|
||||||
|
|
||||||
expect(mockedPauseSession).toHaveBeenCalledWith('SESSION_001')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('暂停成功后 sessionState 应更新为 PAUSED', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
const { taskInfo, stopTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
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('PAUSED 状态下点击开始,应调用 continueSession API', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: {
|
||||||
sessionNum: 'SESSION_001',
|
sessionState: 'PAUSED',
|
||||||
sessionState: 'ONGOING',
|
actualTime: 10,
|
||||||
pointerPosition: 1500000,
|
effectiveTime: 20,
|
||||||
|
effectivenessRatio: 0.8,
|
||||||
|
pointerPosition: 1_200_000,
|
||||||
},
|
},
|
||||||
} as any)
|
} as any)
|
||||||
|
const wrapper = await mountTask()
|
||||||
|
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||||
|
wrapper.vm.timerRunning = true
|
||||||
|
|
||||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
await wrapper.vm.stopTimer()
|
||||||
|
|
||||||
// 先暂停
|
expect(pauseSession).toHaveBeenCalledWith('SESSION_001')
|
||||||
await stopTimer()
|
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
expect(wrapper.vm.taskInfo.actualTime).toBe(10)
|
||||||
|
expect(wrapper.vm.taskInfo.effectiveTime).toBe(20)
|
||||||
// 再开始
|
expect(wrapper.vm.timerRunning).toBe(false)
|
||||||
await startTimer()
|
wrapper.unmount()
|
||||||
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledWith('SESSION_001')
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('PAUSED 状态下点击开始,应调用 loadTaskSession 刷新数据', async () => {
|
it('startTimer continues a paused session and reloads session data', async () => {
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
vi.mocked(continueSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
vi.mocked(startOrContinueStudySession).mockResolvedValue({
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: {
|
data: { ...defaultSessionData, sessionState: 'ONGOING', pointerPosition: 1_200_000 },
|
||||||
sessionNum: 'SESSION_001',
|
|
||||||
sessionState: 'ONGOING',
|
|
||||||
pointerPosition: 1200000,
|
|
||||||
},
|
|
||||||
} as any)
|
} as any)
|
||||||
|
const wrapper = await mountTask()
|
||||||
|
|
||||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
// 挂载时后端返回 PAUSED;手动改为 PAUSED 后,startTimer 应触发 continue
|
||||||
|
wrapper.vm.taskInfo.sessionState = 'PAUSED'
|
||||||
|
await wrapper.vm.startTimer()
|
||||||
|
|
||||||
await stopTimer()
|
expect(continueSession).toHaveBeenCalledWith('SESSION_001')
|
||||||
await startTimer()
|
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
|
||||||
|
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||||
expect(mockedStartOrContinue).toHaveBeenCalledWith('T001')
|
expect(wrapper.vm.timerRunning).toBe(true)
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('ONGOING 状态下点击开始,不应调用 continueSession API', async () => {
|
it('startTimer does not call continue API when session is already ongoing', async () => {
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
const wrapper = await mountTask()
|
||||||
code: 200,
|
wrapper.vm.taskInfo.sessionState = 'ONGOING'
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
|
||||||
} as any)
|
|
||||||
|
|
||||||
const { taskInfo, startTimer } = createSessionSimulator()
|
await wrapper.vm.startTimer()
|
||||||
|
|
||||||
// 直接在 ONGOING 状态调用 startTimer
|
expect(continueSession).not.toHaveBeenCalled()
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
expect(wrapper.vm.timerRunning).toBe(true)
|
||||||
await startTimer()
|
wrapper.unmount()
|
||||||
|
|
||||||
expect(mockedContinueSession).not.toHaveBeenCalled()
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('开始后 timerRunning 应为 true', async () => {
|
it('endTimer refuses empty content without calling API', async () => {
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
const wrapper = await mountTask()
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
|
||||||
} as any)
|
|
||||||
|
|
||||||
const { timerRunning, stopTimer, startTimer } = createSessionSimulator()
|
await wrapper.vm.endTimer('')
|
||||||
|
|
||||||
await stopTimer()
|
expect(ElMessage.warning).toHaveBeenCalledWith('请输入学习总结内容')
|
||||||
expect(timerRunning.value).toBe(false)
|
expect(endSession).not.toHaveBeenCalled()
|
||||||
|
wrapper.unmount()
|
||||||
await startTimer()
|
|
||||||
expect(timerRunning.value).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('endTimer - 结束会话', () => {
|
it('endTimer ends session and navigates to study page', async () => {
|
||||||
it('调用 endSession API 并传递 content', async () => {
|
vi.mocked(endSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
const wrapper = await mountTask()
|
||||||
const { endTimer } = createSessionSimulator()
|
|
||||||
|
|
||||||
await endTimer('学习总结内容')
|
await wrapper.vm.endTimer('学习总结内容')
|
||||||
|
|
||||||
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
expect(endSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||||
|
expect(ElMessage.success).toHaveBeenCalledWith('任务结束')
|
||||||
|
expect(localStorage.getItem('activeSession')).toBeNull()
|
||||||
|
expect(router.currentRoute.value.path).toBe('/study')
|
||||||
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('后端返回 warning 消息时,message 应包含提示信息', async () => {
|
it('endTimer shows warning message returned by backend', async () => {
|
||||||
mockedEndSession.mockResolvedValue({
|
vi.mocked(endSession).mockResolvedValue({
|
||||||
code: 200,
|
code: 200,
|
||||||
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
message: '本次有效学习时间不足10分钟,不计入总学习时间',
|
||||||
} as any)
|
} as any)
|
||||||
|
const wrapper = await mountTask()
|
||||||
|
|
||||||
const { endTimer } = createSessionSimulator()
|
await wrapper.vm.endTimer('学习总结内容')
|
||||||
const res = await endSession('SESSION_001', '内容')
|
|
||||||
|
|
||||||
expect(res.message).toBe('本次有效学习时间不足10分钟,不计入总学习时间')
|
expect(ElMessage.warning).toHaveBeenCalledWith('本次有效学习时间不足10分钟,不计入总学习时间')
|
||||||
expect(res.message).not.toBe('请求成功')
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('content 为空时不调用 API', async () => {
|
it('supports a full pause -> continue -> pause flow', async () => {
|
||||||
const { endTimer } = createSessionSimulator()
|
vi.mocked(pauseSession).mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||||
|
vi.mocked(getSessionDetail).mockResolvedValue({
|
||||||
await endTimer('')
|
|
||||||
|
|
||||||
expect(mockedEndSession).not.toHaveBeenCalled()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('完整暂停→继续→暂停流程', () => {
|
|
||||||
it('多次暂停/继续应正确更新状态和调用 API', async () => {
|
|
||||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedContinueSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
|
||||||
mockedStartOrContinue.mockResolvedValue({
|
|
||||||
code: 200,
|
code: 200,
|
||||||
data: { sessionState: 'ONGOING', pointerPosition: 1500000 },
|
data: { sessionState: 'PAUSED', actualTime: 10, effectiveTime: 20 },
|
||||||
} as any)
|
} 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()
|
||||||
|
|
||||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
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(taskInfo.sessionState).toBe('ONGOING')
|
expect(wrapper.vm.taskInfo.sessionState).toBe('ONGOING')
|
||||||
|
expect(continueSession).toHaveBeenCalledTimes(1)
|
||||||
|
|
||||||
// 第一次暂停
|
await wrapper.vm.stopTimer()
|
||||||
await stopTimer()
|
expect(wrapper.vm.taskInfo.sessionState).toBe('PAUSED')
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
expect(pauseSession).toHaveBeenCalledTimes(2)
|
||||||
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
|
wrapper.unmount()
|
||||||
|
|
||||||
// 继续
|
|
||||||
await startTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledTimes(1)
|
|
||||||
|
|
||||||
// 第二次暂停
|
|
||||||
await stopTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
|
||||||
expect(mockedPauseSession).toHaveBeenCalledTimes(2)
|
|
||||||
|
|
||||||
// 再次继续
|
|
||||||
await startTimer()
|
|
||||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
|
||||||
expect(mockedContinueSession).toHaveBeenCalledTimes(2)
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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(priorityOptions.length).toBe(6)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('priority state management', () => {
|
expect(wrapper.vm.priorityOptions).toEqual([0, 1, 2, 3, 4, 5])
|
||||||
it('initializes with all zeros', () => {
|
expect(wrapper.vm.priority).toEqual({
|
||||||
const priority = reactive({
|
|
||||||
urgency: 0,
|
urgency: 0,
|
||||||
importance: 0,
|
importance: 0,
|
||||||
contentDifficulty: 0,
|
contentDifficulty: 0,
|
||||||
futureValue: 0,
|
futureValue: 0,
|
||||||
subjectivePriority: 0,
|
subjectivePriority: 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(priority.urgency).toBe(0)
|
|
||||||
expect(priority.importance).toBe(0)
|
|
||||||
expect(priority.contentDifficulty).toBe(0)
|
|
||||||
expect(priority.futureValue).toBe(0)
|
|
||||||
expect(priority.subjectivePriority).toBe(0)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('updates individual priority fields', () => {
|
it('builds create payload from real form state and navigates to study', async () => {
|
||||||
const priority = reactive({
|
vi.mocked(request.post).mockResolvedValue({ code: 200, message: '创建任务成功' })
|
||||||
urgency: 0,
|
const wrapper = await mountAt('/add-task')
|
||||||
importance: 0,
|
wrapper.vm.taskName = '学习递归'
|
||||||
contentDifficulty: 0,
|
wrapper.vm.taskDescription = '理解递归的基本概念'
|
||||||
futureValue: 0,
|
wrapper.vm.materialUrl = 'https://example.com/recursion'
|
||||||
subjectivePriority: 0,
|
wrapper.vm.priority.urgency = 3
|
||||||
})
|
wrapper.vm.priority.importance = 4
|
||||||
|
wrapper.vm.priority.contentDifficulty = 2
|
||||||
|
wrapper.vm.priority.futureValue = 5
|
||||||
|
wrapper.vm.priority.subjectivePriority = 3
|
||||||
|
|
||||||
priority.urgency = 3
|
wrapper.vm.createTask()
|
||||||
priority.importance = 5
|
await flushPromises()
|
||||||
|
|
||||||
expect(priority.urgency).toBe(3)
|
expect(request.post).toHaveBeenCalledWith('/tasks', {
|
||||||
expect(priority.importance).toBe(5)
|
|
||||||
expect(priority.contentDifficulty).toBe(0)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('task payload construction', () => {
|
|
||||||
it('builds correct create payload', () => {
|
|
||||||
const taskName = ref('学习递归')
|
|
||||||
const taskDescription = ref('理解递归的基本概念')
|
|
||||||
const materialURL = ref('https://example.com/recursion')
|
|
||||||
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: '学习递归',
|
taskName: '学习递归',
|
||||||
taskDescription: '理解递归的基本概念',
|
taskDescription: '理解递归的基本概念',
|
||||||
materialURL: 'https://example.com/recursion',
|
materialUrl: 'https://example.com/recursion',
|
||||||
urgency: 3,
|
urgency: 3,
|
||||||
importance: 4,
|
importance: 4,
|
||||||
contentDifficulty: 2,
|
contentDifficulty: 2,
|
||||||
futureValue: 5,
|
futureValue: 5,
|
||||||
subjectivePriority: 3,
|
subjectivePriority: 3,
|
||||||
})
|
})
|
||||||
|
expect(ElMessage.success).toHaveBeenCalledWith('创建任务成功')
|
||||||
|
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||||
})
|
})
|
||||||
|
|
||||||
it('builds correct update payload with id', () => {
|
it('loads update data from real API and maps it into form state', async () => {
|
||||||
const taskId = 42
|
vi.mocked(request.get).mockResolvedValue({
|
||||||
const taskName = ref('更新后的任务')
|
code: 200,
|
||||||
const taskDescription = ref('')
|
data: {
|
||||||
const materialURL = ref('')
|
taskNum: 'T001',
|
||||||
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 wrapper = await mountAt('/update-task/42')
|
||||||
const taskDescription = ref('')
|
await flushPromises()
|
||||||
const materialURL = ref('')
|
|
||||||
const priority = reactive({
|
expect(wrapper.vm.isUpdateMode).toBe(true)
|
||||||
urgency: 0,
|
expect(wrapper.vm.taskNum).toBe('T001')
|
||||||
importance: 0,
|
expect(wrapper.vm.taskName).toBe('学习DP')
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('builds update payload with id and navigates to study', async () => {
|
||||||
|
vi.mocked(request.get).mockResolvedValue({
|
||||||
|
code: 200,
|
||||||
|
data: {
|
||||||
|
taskNum: 'T001',
|
||||||
|
taskName: '学习DP',
|
||||||
|
taskDescription: '动态规划',
|
||||||
|
materialUrl: '',
|
||||||
|
urgency: 1,
|
||||||
|
importance: 2,
|
||||||
contentDifficulty: 0,
|
contentDifficulty: 0,
|
||||||
futureValue: 0,
|
futureValue: 3,
|
||||||
subjectivePriority: 0,
|
subjectivePriority: 4,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
vi.mocked(request.put).mockResolvedValue({ code: 200, message: '更新任务成功' })
|
||||||
|
|
||||||
// Simulate loadTask mapping
|
const wrapper = await mountAt('/update-task/42')
|
||||||
taskName.value = apiData.taskName
|
await flushPromises()
|
||||||
taskDescription.value = apiData.taskDescription
|
wrapper.vm.taskName = '更新后的任务'
|
||||||
materialURL.value = apiData.materialURL || apiData.materialUrl || ''
|
wrapper.vm.updateTask()
|
||||||
priority.urgency = apiData.urgency
|
await flushPromises()
|
||||||
priority.importance = apiData.importance
|
|
||||||
priority.contentDifficulty = apiData.contentDifficulty
|
|
||||||
priority.futureValue = apiData.futureValue
|
|
||||||
priority.subjectivePriority = apiData.subjectivePriority
|
|
||||||
|
|
||||||
expect(taskName.value).toBe('学习DP')
|
expect(request.put).toHaveBeenCalledWith('/tasks/42', expect.objectContaining({
|
||||||
expect(materialURL.value).toBe('https://example.com/dp')
|
id: 42,
|
||||||
expect(priority.urgency).toBe(4)
|
taskName: '更新后的任务',
|
||||||
expect(priority.importance).toBe(5)
|
}))
|
||||||
})
|
expect(ElMessage.success).toHaveBeenCalledWith('更新任务成功')
|
||||||
|
await vi.waitFor(() => expect(router.currentRoute.value.name).toBe('study'))
|
||||||
it('handles materialURL with camelCase variant', () => {
|
|
||||||
const apiData = { materialURL: 'https://example.com/a', materialUrl: 'https://example.com/b' }
|
|
||||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
|
||||||
expect(result).toBe('https://example.com/a')
|
|
||||||
})
|
|
||||||
|
|
||||||
it('falls back to empty string when no material URL', () => {
|
|
||||||
const apiData = {} as any
|
|
||||||
const result = apiData.materialURL || apiData.materialUrl || ''
|
|
||||||
expect(result).toBe('')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe('redirect after successful action', () => {
|
|
||||||
it('navigates to study page after create/update', () => {
|
|
||||||
const pushTarget = '/study'
|
|
||||||
expect(pushTarget).toBe('/study')
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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('网络超时')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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()
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+18
-3
@@ -1,7 +1,10 @@
|
|||||||
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) => {
|
||||||
|
const actual = await importOriginal<typeof import('element-plus')>()
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
ElMessage: {
|
ElMessage: {
|
||||||
success: vi.fn(),
|
success: vi.fn(),
|
||||||
error: vi.fn(),
|
error: vi.fn(),
|
||||||
@@ -10,5 +13,17 @@ vi.mock('element-plus', () => ({
|
|||||||
},
|
},
|
||||||
ElMessageBox: {
|
ElMessageBox: {
|
||||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
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)
|
||||||
|
|||||||
@@ -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', () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user