Compare commits
24 Commits
task-1
...
0be2b1c26e
| Author | SHA1 | Date | |
|---|---|---|---|
| 0be2b1c26e | |||
| 7a55063174 | |||
| 15eea25598 | |||
| 0a71a42056 | |||
| 1f44da3c6c | |||
| 97981d5401 | |||
| 887756f4ff | |||
| a82c25b45c | |||
| 0f1a2d8bba | |||
| 439a530978 | |||
| a6ac089e15 | |||
| 52dbc51749 | |||
| c1f00378f2 | |||
| 29db5a4c30 | |||
| 43d3dbde2c | |||
| 2da736aaf3 | |||
| e0f5055740 | |||
| b8a4f1e981 | |||
| aa5e5a654f | |||
| 88ec132579 | |||
| 13846a0b61 | |||
| f35f73dca0 | |||
| 6e74256d66 | |||
| 801c8a670c |
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
.DS_Store
|
||||
coverage
|
||||
.nyc_output
|
||||
playwright-report
|
||||
test-results
|
||||
@@ -28,3 +28,7 @@ coverage
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Test artifacts
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
+16
-5
@@ -1,10 +1,21 @@
|
||||
# --- 构建阶段 ---
|
||||
FROM node:20-alpine AS builder
|
||||
WORKDIR /app
|
||||
|
||||
ARG BUILD_MODE=production
|
||||
|
||||
# 先复制依赖描述文件,利用层缓存
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm install
|
||||
|
||||
# 再复制源码,构建
|
||||
COPY . .
|
||||
RUN npm run type-check && npm run build:${BUILD_MODE}
|
||||
|
||||
# --- 生产阶段 ---
|
||||
FROM nginx:alpine
|
||||
|
||||
# 安装 curl 用于健康检查
|
||||
RUN apk add --no-cache curl
|
||||
|
||||
COPY dist/ /usr/share/nginx/html/
|
||||
COPY --from=builder /app/dist/ /usr/share/nginx/html/
|
||||
RUN chmod -R 755 /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
Vendored
+10
-65
@@ -1,54 +1,21 @@
|
||||
pipeline {
|
||||
agent none // 全局不指定,局部单独声明
|
||||
agent none
|
||||
environment {
|
||||
IMAGE_NAME = 'lpt-fe:0.0'
|
||||
IMAGE_NAME = 'lpt-fe:0.0'
|
||||
CONTAINER_NAME = 'LPT_FE'
|
||||
CONTAINER_PORT = '80'
|
||||
}
|
||||
stages {
|
||||
stage('Install Dependencies') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('构建 Docker 镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm config set cache /.npm
|
||||
npm install
|
||||
'''
|
||||
sh 'docker build --build-arg BUILD_MODE=production -t $IMAGE_NAME .'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Type Check & Build') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('部署容器') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm run type-check
|
||||
npm run build
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Docker Image') {
|
||||
agent any // Jenkins默认节点,有Docker命令
|
||||
steps {
|
||||
sh '''
|
||||
docker build -t $IMAGE_NAME .
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Run Docker Container') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
sh '''
|
||||
docker network create traefik-public || true
|
||||
docker rm -f $CONTAINER_NAME || true
|
||||
docker run -d --name $CONTAINER_NAME \\
|
||||
@@ -60,36 +27,14 @@ pipeline {
|
||||
--label "traefik.http.routers.lpt-fe.tls.certresolver=le" \\
|
||||
--label "traefik.http.routers.lpt-fe.service=lpt-fe" \\
|
||||
--label "traefik.http.services.lpt-fe.loadbalancer.server.port=$CONTAINER_PORT" \\
|
||||
--health-cmd="curl -f http://localhost:80 || exit 1" \\
|
||||
--health-interval=5s \\
|
||||
--health-retries=3 \\
|
||||
--restart=always \\
|
||||
$IMAGE_NAME
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Check Docker Status') {
|
||||
stage('健康检查') {
|
||||
agent any
|
||||
steps {
|
||||
script {
|
||||
def lastStatus = ''
|
||||
timeout(time: 60, unit: 'SECONDS') {
|
||||
waitUntil {
|
||||
def status = sh(
|
||||
script: "docker inspect -f '{{.State.Health.Status}}' $CONTAINER_NAME || echo 'unhealthy'",
|
||||
returnStdout: true
|
||||
).trim()
|
||||
|
||||
if (status != lastStatus) {
|
||||
echo "Container health: ${status}"
|
||||
lastStatus = status
|
||||
}
|
||||
|
||||
return (status == 'healthy')
|
||||
}
|
||||
}
|
||||
}
|
||||
sh 'sleep 5 && docker exec $CONTAINER_NAME curl -f http://localhost:$CONTAINER_PORT/ || (docker logs $CONTAINER_NAME && exit 1)'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+10
-65
@@ -1,54 +1,21 @@
|
||||
pipeline {
|
||||
agent none // 全局不指定,局部单独声明
|
||||
agent none
|
||||
environment {
|
||||
IMAGE_NAME = 'lpt-fe-dev:0.0'
|
||||
IMAGE_NAME = 'lpt-fe-dev:0.0'
|
||||
CONTAINER_NAME = 'LPT_FE-dev'
|
||||
CONTAINER_PORT = '80'
|
||||
}
|
||||
stages {
|
||||
stage('Install Dependencies') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('构建 Docker 镜像') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm config set cache /.npm
|
||||
npm install
|
||||
'''
|
||||
sh 'docker build --build-arg BUILD_MODE=dev -t $IMAGE_NAME .'
|
||||
}
|
||||
}
|
||||
|
||||
stage('Type Check & Build') {
|
||||
agent {
|
||||
docker {
|
||||
image 'node:20-alpine'
|
||||
args '-v ${WORKSPACE}/.npm:/.npm -v ${WORKSPACE}/node_modules:/app/node_modules'
|
||||
}
|
||||
}
|
||||
stage('部署容器') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
npm run type-check
|
||||
npm run build:dev
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Build Docker Image') {
|
||||
agent any // Jenkins默认节点,有Docker命令
|
||||
steps {
|
||||
sh '''
|
||||
docker build -t $IMAGE_NAME .
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Run Docker Container') {
|
||||
agent any
|
||||
steps {
|
||||
sh '''
|
||||
sh '''
|
||||
docker network create traefik-public || true
|
||||
docker rm -f $CONTAINER_NAME || true
|
||||
docker run -d --name $CONTAINER_NAME \\
|
||||
@@ -60,36 +27,14 @@ pipeline {
|
||||
--label "traefik.http.routers.lpt-fe-dev.tls.certresolver=le" \\
|
||||
--label "traefik.http.routers.lpt-fe-dev.service=lpt-fe-dev" \\
|
||||
--label "traefik.http.services.lpt-fe-dev.loadbalancer.server.port=$CONTAINER_PORT" \\
|
||||
--health-cmd="curl -f http://localhost:80 || exit 1" \\
|
||||
--health-interval=5s \\
|
||||
--health-retries=3 \\
|
||||
--restart=always \\
|
||||
$IMAGE_NAME
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('Check Docker Status') {
|
||||
stage('健康检查') {
|
||||
agent any
|
||||
steps {
|
||||
script {
|
||||
def lastStatus = ''
|
||||
timeout(time: 60, unit: 'SECONDS') {
|
||||
waitUntil {
|
||||
def status = sh(
|
||||
script: "docker inspect -f '{{.State.Health.Status}}' $CONTAINER_NAME || echo 'unhealthy'",
|
||||
returnStdout: true
|
||||
).trim()
|
||||
|
||||
if (status != lastStatus) {
|
||||
echo "Container health: ${status}"
|
||||
lastStatus = status
|
||||
}
|
||||
|
||||
return (status == 'healthy')
|
||||
}
|
||||
}
|
||||
}
|
||||
sh 'sleep 5 && docker exec $CONTAINER_NAME curl -f http://localhost:$CONTAINER_PORT/ || (docker logs $CONTAINER_NAME && exit 1)'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Auth guard', () => {
|
||||
test('redirects to /login when not authenticated', async ({ page }) => {
|
||||
// Ensure no auth state
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.removeItem('isLoggedIn'));
|
||||
await page.goto('/welcome');
|
||||
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
await expect(page.locator('.login-page')).toBeVisible();
|
||||
});
|
||||
|
||||
test('redirects / to /login when not authenticated', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.removeItem('isLoggedIn'));
|
||||
await page.goto('/');
|
||||
|
||||
await expect(page).toHaveURL(/\/login/);
|
||||
});
|
||||
|
||||
test('allows access to /welcome when authenticated', async ({ page }) => {
|
||||
await page.route('**/api/review/feed', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
|
||||
await expect(page).toHaveURL(/\/welcome/);
|
||||
await expect(page.locator('.welcome-page')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockLoginSuccess = { code: 200, message: '登录成功' };
|
||||
const mockLoginFailure = { code: 401, message: '账号或密码错误' };
|
||||
const mockTasks = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Login page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await page.waitForSelector('.login-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('renders the login form with title and inputs', async ({ page }) => {
|
||||
await expect(page.locator('h2')).toContainText('账号登录');
|
||||
await expect(page.locator('.login-form')).toBeVisible();
|
||||
// Element Plus inputs
|
||||
const inputs = page.locator('.el-input');
|
||||
await expect(inputs).toHaveCount(2);
|
||||
await expect(page.locator('.submit-btn')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation errors when fields are empty', async ({ page }) => {
|
||||
await page.locator('.submit-btn').click();
|
||||
// Element Plus validation shows error messages
|
||||
await expect(page.locator('.el-form-item__error').first()).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('shows error on invalid credentials', async ({ page }) => {
|
||||
await page.route('**/api/login**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockLoginFailure),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) }),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
// Fill in inputs using Element Plus el-input inner input
|
||||
const usernameInput = page.locator('.el-form-item').filter({ hasText: '账号' }).locator('input');
|
||||
const passwordInput = page.locator('.el-form-item').filter({ hasText: '密码' }).locator('input');
|
||||
await usernameInput.fill('wronguser');
|
||||
await passwordInput.fill('wrongpass');
|
||||
await page.locator('.submit-btn').click();
|
||||
|
||||
// Element Plus error message appears in a popup
|
||||
await expect(page.locator('.el-message--error')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('successful login navigates to /welcome', async ({ page }) => {
|
||||
await page.route('**/api/login**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockLoginSuccess),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) }),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
const usernameInput = page.locator('.el-form-item').filter({ hasText: '账号' }).locator('input');
|
||||
const passwordInput = page.locator('.el-form-item').filter({ hasText: '密码' }).locator('input');
|
||||
await usernameInput.fill('admin');
|
||||
await passwordInput.fill('password123');
|
||||
await page.locator('.submit-btn').click();
|
||||
|
||||
await expect(page).toHaveURL(/\/welcome/, { timeout: 10_000 });
|
||||
const isLoggedIn = await page.evaluate(() => localStorage.getItem('isLoggedIn'));
|
||||
expect(isLoggedIn).toBe('true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasks = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Header navigation', () => {
|
||||
test('shows brand title on login page', async ({ page }) => {
|
||||
await page.goto('/login');
|
||||
await expect(page.locator('.login-page')).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.locator('.login-panel h1')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows logout button on authenticated pages', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .logout-btn')).toBeVisible();
|
||||
});
|
||||
|
||||
test('logout clears auth and redirects to /login', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await page.locator('.head .logout-btn').click();
|
||||
await expect(page).toHaveURL(/\/login/, { timeout: 5000 });
|
||||
const isLoggedIn = await page.evaluate(() => localStorage.getItem('isLoggedIn'));
|
||||
expect(isLoggedIn).toBeNull();
|
||||
});
|
||||
|
||||
test('back button shows on sub-pages and navigates to /welcome', async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockTasks) }),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .back-btn')).toBeVisible();
|
||||
await page.locator('.head .back-btn').click();
|
||||
await expect(page).toHaveURL(/\/welcome/);
|
||||
});
|
||||
|
||||
test('no back button on welcome page', async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.head .back-btn')).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasksData = {
|
||||
code: 200,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
taskNum: 'T001',
|
||||
taskName: '学习 Vue3',
|
||||
reportCount: 3,
|
||||
fragmentCount: 5,
|
||||
effectiveTime: '2h 30m',
|
||||
},
|
||||
{
|
||||
taskNum: 'T002',
|
||||
taskName: '学习 TypeScript',
|
||||
reportCount: 1,
|
||||
fragmentCount: 2,
|
||||
effectiveTime: '1h 15m',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const mockTasksEmpty = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
test.describe('Review page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksData),
|
||||
}),
|
||||
);
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('displays summary metrics and task table', async ({ page }) => {
|
||||
await expect(page.locator('.metric-card')).toHaveCount(3);
|
||||
// Check metric values
|
||||
await expect(page.locator('.metric-card').first().locator('strong')).toContainText('2');
|
||||
// Check table rows
|
||||
await expect(page.locator('.el-table__row')).toHaveCount(2);
|
||||
});
|
||||
|
||||
test('shows empty state when no tasks', async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksEmpty),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/review');
|
||||
await page.waitForSelector('.review-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.metric-card').first().locator('strong')).toContainText('0');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockSessionOngoing = {
|
||||
code: 200,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
taskName: '学习 Vue3',
|
||||
taskNum: 'T001',
|
||||
startTime: '2026-05-30T10:00:00',
|
||||
endTime: null,
|
||||
lastStartTime: '2026-05-30T10:00:00',
|
||||
actualTime: 0,
|
||||
effectiveTime: 0,
|
||||
effectivenessRatio: '--',
|
||||
pointerPosition: 1500000,
|
||||
systemMessage: '',
|
||||
},
|
||||
};
|
||||
|
||||
const mockSessionPaused = {
|
||||
code: 200,
|
||||
data: {
|
||||
...mockSessionOngoing.data,
|
||||
sessionState: 'PAUSED',
|
||||
lastStartTime: '2026-05-30T10:05:00',
|
||||
actualTime: 300,
|
||||
effectiveTime: 300,
|
||||
},
|
||||
};
|
||||
|
||||
const mockApiResponse = (code = 200, data: any = null, message = '请求成功') => ({
|
||||
code,
|
||||
message,
|
||||
data,
|
||||
});
|
||||
|
||||
test.describe('StartTask - 暂停后继续', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// 模拟登录
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
|
||||
// mock startOrContinue API(初始加载返回 ONGOING 状态)
|
||||
await page.route('**/api/tasks/*/study-sessions/start-or-continue', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockSessionOngoing),
|
||||
}),
|
||||
);
|
||||
|
||||
// mock fragments API
|
||||
await page.route('**/api/study-sessions/*/all-fragments', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, [])),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('暂停后点击开始,应触发 continue API', async ({ page }) => {
|
||||
// 记录 API 调用
|
||||
const apiCalls: string[] = [];
|
||||
|
||||
// mock pause API
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) => {
|
||||
apiCalls.push('pause');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
// mock continue API
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/continue', (route) => {
|
||||
apiCalls.push('continue');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
// 进入 start-task 页面
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
|
||||
// 等待计时器启动
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// 点击暂停按钮
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
|
||||
// 验证暂停 API 被调用
|
||||
expect(apiCalls).toContain('pause');
|
||||
|
||||
// 验证状态变为已暂停
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 点击开始按钮
|
||||
await page.locator('button', { hasText: '开始' }).click();
|
||||
|
||||
// 验证 continue API 被调用
|
||||
expect(apiCalls).toContain('continue');
|
||||
|
||||
// 验证状态恢复为进行中
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
});
|
||||
|
||||
test('暂停后点击开始,不暂停时开始不应触发 continue API', async ({ page }) => {
|
||||
const apiCalls: string[] = [];
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) => {
|
||||
apiCalls.push('pause');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/continue', (route) => {
|
||||
apiCalls.push('continue');
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.status-text')).toContainText('进行中');
|
||||
|
||||
// ONGOING 状态下,开始按钮是 disabled 的,不应触发 continue
|
||||
const startBtn = page.locator('button', { hasText: '开始' });
|
||||
await expect(startBtn).toBeDisabled();
|
||||
|
||||
// continue API 不应被调用
|
||||
expect(apiCalls).not.toContain('continue');
|
||||
});
|
||||
|
||||
test('暂停后结束会话,应正确调用 ended API 并展示提示', async ({ page }) => {
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/pause', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse()),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.route('**/api/study-sessions/SESSION_001/study-sessions/ended', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockApiResponse(200, null, '本次有效学习时间不足10分钟,不计入总学习时间')),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/start-task/T001');
|
||||
await page.waitForSelector('.start-page', { timeout: 10_000 });
|
||||
|
||||
// 暂停
|
||||
await page.locator('button', { hasText: '暂停' }).click();
|
||||
await expect(page.locator('.status-text')).toContainText('已暂停');
|
||||
|
||||
// 结束会话
|
||||
await page.locator('button', { hasText: '结束会话' }).click();
|
||||
|
||||
// 在弹窗中输入总结内容
|
||||
await page.locator('.el-dialog textarea').fill('测试总结');
|
||||
await page.locator('.el-dialog button', { hasText: '确认结束' }).click();
|
||||
|
||||
// 应看到 warning 提示(有效时间不足)
|
||||
await expect(page.locator('.el-message--warning')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockTasks = {
|
||||
code: 200,
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: 1,
|
||||
taskNum: 'T001',
|
||||
taskName: '学习 Vue3 组合式 API',
|
||||
taskDescription: '掌握 Composition API 的核心概念',
|
||||
taskPriority: 5,
|
||||
materialUrl: 'https://vuejs.org/guide',
|
||||
lastLearningStatus: '进行中',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
taskNum: 'T002',
|
||||
taskName: 'TypeScript 类型体操',
|
||||
taskDescription: '练习 TypeScript 高级类型',
|
||||
taskPriority: 3,
|
||||
materialUrl: '',
|
||||
lastLearningStatus: '未开始',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const mockTasksEmpty = { code: 200, data: { records: [] } };
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
const authAndNavigate = async (page: any) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
};
|
||||
|
||||
test.describe('Study page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) => {
|
||||
const url = route.request().url();
|
||||
if (url.includes('/tasks') && !url.includes('/tasks/')) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasks),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: {} }),
|
||||
});
|
||||
});
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
|
||||
await authAndNavigate(page);
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('displays task list with names and priorities', async ({ page }) => {
|
||||
const taskItems = page.locator('.task-list-item');
|
||||
await expect(taskItems).toHaveCount(2);
|
||||
await expect(taskItems.first().locator('.task-name')).toContainText('学习 Vue3 组合式 API');
|
||||
await expect(taskItems.nth(1).locator('.task-name')).toContainText('TypeScript 类型体操');
|
||||
});
|
||||
|
||||
test('selecting a task shows its details', async ({ page }) => {
|
||||
const taskItems = page.locator('.task-list-item');
|
||||
await taskItems.nth(1).click();
|
||||
await expect(page.locator('.detail-head h3')).toContainText('TypeScript 类型体操');
|
||||
});
|
||||
|
||||
test('clicking add navigates to add-task form', async ({ page }) => {
|
||||
await page.locator('.action-card').locator('button', { hasText: '添加任务' }).click();
|
||||
await expect(page).toHaveURL(/\/add-task/);
|
||||
});
|
||||
|
||||
test('clicking update navigates to update-task form', async ({ page }) => {
|
||||
await page.locator('.action-card').locator('button', { hasText: '更新任务' }).click();
|
||||
await expect(page).toHaveURL(/\/update-task/);
|
||||
});
|
||||
|
||||
test('delete task removes it from the list', async ({ page }) => {
|
||||
await page.route('**/api/tasks/1', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '删除成功' }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.locator('.action-card').locator('button', { hasText: '删除任务' }).click();
|
||||
await expect(page.locator('.task-list-item')).toHaveCount(1, { timeout: 5000 });
|
||||
});
|
||||
|
||||
test('shows empty state when no tasks', async ({ page }) => {
|
||||
await page.route('**/api/tasks**', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTasksEmpty),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/study');
|
||||
await page.waitForSelector('.study-page', { timeout: 10_000 });
|
||||
await expect(page.locator('.el-empty')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const mockFeed = { code: 200, data: [] };
|
||||
|
||||
const loginAndGo = async (page: any, url: string) => {
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto(url);
|
||||
await page.waitForSelector('.task-form-page', { timeout: 10_000 });
|
||||
};
|
||||
|
||||
test.describe('Task form', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/review/feed**', (route) =>
|
||||
route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(mockFeed) }),
|
||||
);
|
||||
});
|
||||
|
||||
test('add-task form renders empty fields and "添加" button', async ({ page }) => {
|
||||
await loginAndGo(page, '/add-task');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input')).toHaveValue('');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务描述' }).locator('textarea')).toHaveValue('');
|
||||
await expect(page.locator('.action-row button').first()).toContainText('添加');
|
||||
});
|
||||
|
||||
test('submitting add-task sends POST and navigates to /study', async ({ page }) => {
|
||||
await page.route('**/api/tasks', (route) => {
|
||||
if (route.request().method() === 'POST') {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '创建成功' }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ code: 200, data: { records: [] } }) });
|
||||
});
|
||||
await loginAndGo(page, '/add-task');
|
||||
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input').fill('新学习任务');
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务描述' }).locator('textarea').fill('这是一个测试任务');
|
||||
await page.locator('.action-row button').first().click();
|
||||
|
||||
await expect(page).toHaveURL(/\/study/, { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('update-task loads existing data and submits PUT', async ({ page }) => {
|
||||
const mockTask = {
|
||||
code: 200,
|
||||
data: {
|
||||
id: 1,
|
||||
taskName: '已有任务',
|
||||
taskDescription: '已有描述',
|
||||
materialURL: 'https://example.com',
|
||||
urgency: 3,
|
||||
importance: 4,
|
||||
contentDifficulty: 2,
|
||||
futureValue: 5,
|
||||
subjectivePriority: 1,
|
||||
},
|
||||
};
|
||||
|
||||
await page.route('**/api/tasks/1', (route) => {
|
||||
if (route.request().method() === 'PUT') {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, message: '更新成功' }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mockTask),
|
||||
});
|
||||
});
|
||||
|
||||
await loginAndGo(page, '/update-task/1');
|
||||
await expect(page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input')).toHaveValue('已有任务');
|
||||
await expect(page.locator('.action-row button').first()).toContainText('更新');
|
||||
|
||||
await page.locator('.el-form-item').filter({ hasText: '任务名称' }).locator('input').fill('更新后的任务');
|
||||
await page.locator('.action-row button').first().click();
|
||||
|
||||
await expect(page).toHaveURL(/\/study/, { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('cancel navigates back to /study', async ({ page }) => {
|
||||
await loginAndGo(page, '/add-task');
|
||||
await page.locator('.action-row button').nth(1).click();
|
||||
await expect(page).toHaveURL(/\/study/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Welcome page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.route('**/api/review/feed', (route) =>
|
||||
route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ code: 200, data: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await page.goto('/login');
|
||||
await page.evaluate(() => localStorage.setItem('isLoggedIn', 'true'));
|
||||
await page.goto('/welcome');
|
||||
await page.waitForSelector('.welcome-page', { timeout: 10_000 });
|
||||
});
|
||||
|
||||
test('shows welcome banner and quick action cards', async ({ page }) => {
|
||||
await expect(page.locator('.page-title')).toContainText('欢迎回来');
|
||||
await expect(page.locator('.page-subtitle')).toBeVisible();
|
||||
await expect(page.locator('.quick-card')).toHaveCount(2);
|
||||
});
|
||||
|
||||
test('clicking start study navigates to /study', async ({ page }) => {
|
||||
await page.locator('.quick-card').first().locator('button').click();
|
||||
await expect(page).toHaveURL(/\/study/);
|
||||
});
|
||||
|
||||
test('clicking start review navigates to /review', async ({ page }) => {
|
||||
await page.locator('.quick-card').nth(1).locator('button').click();
|
||||
await expect(page).toHaveURL(/\/review/);
|
||||
});
|
||||
});
|
||||
+11
-2
@@ -9,7 +9,11 @@
|
||||
"build": "vite build --mode production",
|
||||
"preview": "vite preview",
|
||||
"build-only": "vite build",
|
||||
"type-check": "vue-tsc --build --force"
|
||||
"type-check": "vue-tsc --build --force",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:ui": "playwright test --ui"
|
||||
},
|
||||
"dependencies": {
|
||||
"async-validator": "^4.2.5",
|
||||
@@ -23,13 +27,18 @@
|
||||
"vue-router": "^4.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@tsconfig/node20": "^20.1.4",
|
||||
"@types/jsdom": "^28.0.3",
|
||||
"@types/node": "^20.17.0",
|
||||
"@vitejs/plugin-vue": "^5.1.4",
|
||||
"@vue/test-utils": "^2.4.10",
|
||||
"@vue/tsconfig": "^0.5.1",
|
||||
"jsdom": "^24.1.3",
|
||||
"npm-run-all2": "^7.0.1",
|
||||
"typescript": "~5.6.0",
|
||||
"vite": "^5.4.10",
|
||||
"vitest": "^2.1.9",
|
||||
"vue-tsc": "^2.1.6"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: false,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: 1,
|
||||
reporter: 'list',
|
||||
use: {
|
||||
baseURL: 'http://localhost:5158',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
channel: 'chrome',
|
||||
},
|
||||
},
|
||||
],
|
||||
webServer: {
|
||||
command: 'pnpm dev',
|
||||
url: 'http://localhost:5158',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
Generated
+2782
File diff suppressed because it is too large
Load Diff
+6
-7
@@ -15,9 +15,11 @@ const route = useRoute();
|
||||
<MyHead />
|
||||
</el-header>
|
||||
<el-main class="shell-main">
|
||||
<Transition name="fade-up" mode="out-in">
|
||||
<RouterView :key="route.fullPath" />
|
||||
</Transition>
|
||||
<RouterView v-slot="{ Component }">
|
||||
<Transition name="fade-up" mode="out-in">
|
||||
<component :is="Component" :key="route.fullPath" />
|
||||
</Transition>
|
||||
</RouterView>
|
||||
</el-main>
|
||||
<el-footer class="shell-footer">
|
||||
<MyFooter />
|
||||
@@ -45,10 +47,7 @@ const route = useRoute();
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.shell-main {
|
||||
}.shell-main {
|
||||
max-width: 1240px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import { login, logout } from '@/api/login'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('login API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('login sends POST to /login with credentials', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, message: 'OK' })
|
||||
const result = await login('admin', '123456')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/login', { username: 'admin', password: '123456' })
|
||||
expect(result).toEqual({ code: 200, message: 'OK' })
|
||||
})
|
||||
|
||||
it('logout sends POST to /logout', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, message: '已退出' })
|
||||
const result = await logout()
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/logout')
|
||||
expect(result).toEqual({ code: 200, message: '已退出' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('reportFragments API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('createFragments sends POST with sessionNum and content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
const result = await createFragments('S001', '学习了递归')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/report-fragments', {
|
||||
sessionNum: 'S001',
|
||||
content: '学习了递归',
|
||||
})
|
||||
expect(result).toEqual({ code: 200, data: { id: 1 } })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import { getReviewFeed, getReportDetail, getFragmentDetail, getTaskReview } from '@/api/review'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('review API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('getReviewFeed calls GET /review/feed with limit', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
const result = await getReviewFeed(10)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/feed', { limit: 10 })
|
||||
expect(result).toEqual({ code: 200, data: [] })
|
||||
})
|
||||
|
||||
it('getReviewFeed uses default limit of 30', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
|
||||
await getReviewFeed()
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/feed', { limit: 30 })
|
||||
})
|
||||
|
||||
it('getReportDetail calls GET /review/report/:id', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
const result = await getReportDetail(1)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/report/1')
|
||||
expect(result).toEqual({ code: 200, data: { id: 1 } })
|
||||
})
|
||||
|
||||
it('getFragmentDetail calls GET /review/fragment/:id', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 5 } })
|
||||
await getFragmentDetail(5)
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/fragment/5')
|
||||
})
|
||||
|
||||
it('getTaskReview calls GET /review/task/:taskNum', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
|
||||
await getTaskReview('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/review/task/T001')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/utils/request', () => ({
|
||||
default: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
import {
|
||||
continueSession,
|
||||
pauseSession,
|
||||
endSession,
|
||||
startOrContinueStudySession,
|
||||
getSessionDetail,
|
||||
} from '@/api/studySessions'
|
||||
|
||||
const mockedRequest = vi.mocked(request)
|
||||
|
||||
describe('studySessions API', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('continueSession sends POST to correct endpoint', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await continueSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith('/study-sessions/S001/study-sessions/continue')
|
||||
})
|
||||
|
||||
it('pauseSession sends POST with endTime param when provided', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
const endTime = new Date('2024-01-15T10:30:00Z')
|
||||
await pauseSession('S001', endTime)
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/pause',
|
||||
null,
|
||||
{ params: { endTime: endTime.toISOString() } }
|
||||
)
|
||||
})
|
||||
|
||||
it('pauseSession sends POST with null params when endTime not provided', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await pauseSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/pause',
|
||||
null,
|
||||
{ params: null }
|
||||
)
|
||||
})
|
||||
|
||||
it('endSession sends POST with default content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await endSession('S001')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '任务结束' }
|
||||
)
|
||||
})
|
||||
|
||||
it('endSession sends POST with custom content', async () => {
|
||||
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||
await endSession('S001', '自定义结束')
|
||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
||||
'/study-sessions/S001/study-sessions/ended',
|
||||
{ content: '自定义结束' }
|
||||
)
|
||||
})
|
||||
|
||||
it('startOrContinueStudySession sends GET to correct endpoint', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { sessionNum: 'S002' } })
|
||||
const result = await startOrContinueStudySession('T001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/tasks/T001/study-sessions/start-or-continue')
|
||||
expect(result).toEqual({ code: 200, data: { sessionNum: 'S002' } })
|
||||
})
|
||||
|
||||
it('getSessionDetail sends GET to correct endpoint', async () => {
|
||||
mockedRequest.get.mockResolvedValue({ code: 200, data: { id: 1 } })
|
||||
await getSessionDetail('S001')
|
||||
expect(mockedRequest.get).toHaveBeenCalledWith('/study-sessions/S001')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createRouter, createMemoryHistory } from 'vue-router'
|
||||
import { reactive, ref } from 'vue'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock Element Plus
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
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', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
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.isReady()
|
||||
|
||||
// Simulate submitForm logic
|
||||
const username = 'admin'
|
||||
const password = '123456'
|
||||
const result = await login(username, password)
|
||||
|
||||
if (result.code === 200) {
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
ElMessage.success(result.message)
|
||||
await router.push('/welcome')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBe('true')
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('shows error message on failed login', async () => {
|
||||
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
|
||||
|
||||
const result = await login('admin', 'wrong')
|
||||
if (result.code !== 200) {
|
||||
ElMessage.error(result.message)
|
||||
}
|
||||
|
||||
expect(ElMessage.error).toHaveBeenCalledWith('密码错误')
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not submit when already loading', async () => {
|
||||
const loading = ref(true)
|
||||
// Simulate guard: if (!formEl || loading.value) return;
|
||||
if (loading.value) {
|
||||
// Early return - no API call
|
||||
}
|
||||
expect(login).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
vi.mock('@/api/login', () => ({
|
||||
login: vi.fn(),
|
||||
logout: vi.fn().mockResolvedValue({ code: 200 }),
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { logout } from '@/api/login'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
describe('MyHead.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe('route-based computed properties', () => {
|
||||
it('isLoginRoute is true when path is /login', () => {
|
||||
const routePath = ref('/login')
|
||||
const isLoginRoute = computed(() => routePath.value === '/login')
|
||||
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')
|
||||
|
||||
// Simulate handleLogout
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Backend failure shouldn't block logout
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
|
||||
it('clears login state even when API call fails', async () => {
|
||||
vi.mocked(logout).mockRejectedValue(new Error('Network error'))
|
||||
localStorage.setItem('isLoggedIn', 'true')
|
||||
|
||||
try {
|
||||
await logout()
|
||||
} catch {
|
||||
// Expected
|
||||
} finally {
|
||||
localStorage.removeItem('isLoggedIn')
|
||||
ElMessage.success('已退出登录')
|
||||
}
|
||||
|
||||
expect(localStorage.getItem('isLoggedIn')).toBeNull()
|
||||
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,276 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
// Mock API
|
||||
vi.mock('@/api/studySessions', () => ({
|
||||
continueSession: vi.fn(),
|
||||
pauseSession: vi.fn(),
|
||||
endSession: vi.fn(),
|
||||
startOrContinueStudySession: vi.fn(),
|
||||
getSessionDetail: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/reportFragments', () => ({
|
||||
getFragmentsBySession: vi.fn(),
|
||||
updateFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import {
|
||||
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',
|
||||
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 暂停/继续逻辑', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('stopTimer - 暂停', () => {
|
||||
it('调用 pauseSession API', async () => {
|
||||
mockedPauseSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
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,
|
||||
data: {
|
||||
sessionNum: 'SESSION_001',
|
||||
sessionState: 'ONGOING',
|
||||
pointerPosition: 1500000,
|
||||
},
|
||||
} as any)
|
||||
|
||||
const { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
// 先暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
|
||||
// 再开始
|
||||
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('调用 endSession API 并传递 content', async () => {
|
||||
mockedEndSession.mockResolvedValue({ code: 200, message: '请求成功' } as any)
|
||||
const { endTimer } = createSessionSimulator()
|
||||
|
||||
await endTimer('学习总结内容')
|
||||
|
||||
expect(mockedEndSession).toHaveBeenCalledWith('SESSION_001', '学习总结内容')
|
||||
})
|
||||
|
||||
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('多次暂停/继续应正确更新状态和调用 API', 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 { taskInfo, stopTimer, startTimer } = createSessionSimulator()
|
||||
|
||||
// 初始状态
|
||||
expect(taskInfo.sessionState).toBe('ONGOING')
|
||||
|
||||
// 第一次暂停
|
||||
await stopTimer()
|
||||
expect(taskInfo.sessionState).toBe('PAUSED')
|
||||
expect(mockedPauseSession).toHaveBeenCalledTimes(1)
|
||||
|
||||
// 继续
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref, reactive } from 'vue'
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
describe('TaskForm.vue logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('priorityOptions', () => {
|
||||
it('contains values 0-5', () => {
|
||||
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', () => {
|
||||
it('initializes with all zeros', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 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', () => {
|
||||
const priority = reactive({
|
||||
urgency: 0,
|
||||
importance: 0,
|
||||
contentDifficulty: 0,
|
||||
futureValue: 0,
|
||||
subjectivePriority: 0,
|
||||
})
|
||||
|
||||
priority.urgency = 3
|
||||
priority.importance = 5
|
||||
|
||||
expect(priority.urgency).toBe(3)
|
||||
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: '学习递归',
|
||||
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',
|
||||
taskDescription: '动态规划',
|
||||
materialUrl: 'https://example.com/dp',
|
||||
urgency: 4,
|
||||
importance: 5,
|
||||
contentDifficulty: 3,
|
||||
futureValue: 4,
|
||||
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 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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const mockInfo = vi.fn()
|
||||
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', () => ({
|
||||
createFragments: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createFragments } from '@/api/reportFragments'
|
||||
|
||||
describe('useStudyFragment composable logic', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockConfirm.mockResolvedValue('confirm')
|
||||
})
|
||||
|
||||
it('openFragmentDialog resets content and shows dialog', () => {
|
||||
const fragmentContent = ref('old content')
|
||||
const fragmentsDialogVisible = ref(false)
|
||||
|
||||
fragmentContent.value = ''
|
||||
fragmentsDialogVisible.value = true
|
||||
|
||||
expect(fragmentContent.value).toBe('')
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('closeFragmentDialog hides dialog on confirm', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
mockInfo('已取消生成')
|
||||
})
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
expect(mockInfo).toHaveBeenCalledWith('已取消生成')
|
||||
})
|
||||
|
||||
it('closeFragmentDialog keeps dialog open on cancel', async () => {
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
mockConfirm.mockRejectedValue('cancel')
|
||||
|
||||
try {
|
||||
await mockConfirm('确定取消生成吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning',
|
||||
}).then(() => {
|
||||
fragmentsDialogVisible.value = false
|
||||
})
|
||||
} catch {
|
||||
// User cancelled
|
||||
}
|
||||
|
||||
expect(fragmentsDialogVisible.value).toBe(true)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment warns if content is empty', async () => {
|
||||
const fragmentContent = ref(' ')
|
||||
|
||||
if (!fragmentContent.value.trim()) {
|
||||
mockWarning('请输入学习内容!')
|
||||
}
|
||||
|
||||
expect(mockWarning).toHaveBeenCalledWith('请输入学习内容!')
|
||||
expect(createFragments).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment calls API and shows success', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 200 } as any)
|
||||
const fragmentContent = ref('学习了递归算法')
|
||||
const fragmentsDialogVisible = ref(true)
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
const res = await createFragments('S001', fragmentContent.value)
|
||||
if (res.code === 200) {
|
||||
mockSuccess('学习残片生成成功!')
|
||||
fragmentsDialogVisible.value = false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
expect(createFragments).toHaveBeenCalledWith('S001', '学习了递归算法')
|
||||
expect(mockSuccess).toHaveBeenCalledWith('学习残片生成成功!')
|
||||
expect(fragmentsDialogVisible.value).toBe(false)
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles API failure', async () => {
|
||||
vi.mocked(createFragments).mockResolvedValue({ code: 500, message: '生成失败' } as any)
|
||||
const fragmentContent = ref('学习内容')
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
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('生成失败')
|
||||
})
|
||||
|
||||
it('confirmGenerateFragment handles network error', async () => {
|
||||
vi.mocked(createFragments).mockRejectedValue(new Error('网络超时'))
|
||||
const fragmentContent = ref('学习内容')
|
||||
|
||||
if (fragmentContent.value.trim()) {
|
||||
await mockConfirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
}).then(async () => {
|
||||
try {
|
||||
await createFragments('S001', fragmentContent.value)
|
||||
} catch (error: any) {
|
||||
mockError(error.message || '请求失败')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
expect(mockError).toHaveBeenCalledWith('网络超时')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
// We test the timer composable logic directly since it's a pure Vue composable
|
||||
// Extract the logic to test it in isolation
|
||||
|
||||
describe('useTimer', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
// Test the core timer logic that the composable uses
|
||||
it('formatTime converts seconds to HH:MM:SS', () => {
|
||||
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')
|
||||
expect(formatTime(61)).toBe('00:01:01')
|
||||
expect(formatTime(3661)).toBe('01:01:01')
|
||||
expect(formatTime(59)).toBe('00:00:59')
|
||||
expect(formatTime(3600)).toBe('01:00:00')
|
||||
})
|
||||
|
||||
it('formatTime handles large values', () => {
|
||||
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(86399)).toBe('23:59:59')
|
||||
expect(formatTime(100000)).toBe('27:46:40')
|
||||
})
|
||||
|
||||
it('timer increments elapsedSeconds over time', () => {
|
||||
let elapsed = 0
|
||||
const interval = setInterval(() => {
|
||||
elapsed++
|
||||
}, 1000)
|
||||
|
||||
vi.advanceTimersByTime(3000)
|
||||
expect(elapsed).toBe(3)
|
||||
|
||||
vi.advanceTimersByTime(2000)
|
||||
expect(elapsed).toBe(5)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createRouter, createMemoryHistory } from 'vue-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', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
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 () => {
|
||||
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.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
it('allows authenticated user to access protected route', async () => {
|
||||
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.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
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.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
|
||||
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.isReady()
|
||||
expect(router.currentRoute.value.path).toBe('/login')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
import { vi } from 'vitest'
|
||||
|
||||
// Mock Element Plus components globally
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
ElMessageBox: {
|
||||
confirm: vi.fn().mockResolvedValue('confirm'),
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,131 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const { mockGet, mockPost, mockPut, mockDel } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
mockDel: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('axios', () => ({
|
||||
default: {
|
||||
create: vi.fn(() => ({
|
||||
get: mockGet,
|
||||
post: mockPost,
|
||||
put: mockPut,
|
||||
delete: mockDel,
|
||||
interceptors: {
|
||||
request: { use: vi.fn() },
|
||||
response: { use: vi.fn() },
|
||||
},
|
||||
})),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('element-plus', () => ({
|
||||
ElMessage: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warning: vi.fn(),
|
||||
info: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
import request from '@/utils/request'
|
||||
|
||||
describe('request utility', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('get', () => {
|
||||
it('should call axios.get with url and params wrapped', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'test' } })
|
||||
const result = await request.get('/test', { id: 1 })
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: { id: 1 } })
|
||||
expect(result).toEqual({ code: 200, data: 'test' })
|
||||
})
|
||||
|
||||
it('should default to empty params object', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'test' } })
|
||||
await request.get('/test')
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: {} })
|
||||
})
|
||||
|
||||
it('should reject when response code is not 200', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 400, message: 'Bad request' } })
|
||||
await expect(request.get('/test')).rejects.toEqual({ code: 400, message: 'Bad request' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('post', () => {
|
||||
it('should call axios.post with url, data, and empty config', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'created' } })
|
||||
const result = await request.post('/test', { name: 'foo' })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', { name: 'foo' }, {})
|
||||
expect(result).toEqual({ code: 200, data: 'created' })
|
||||
})
|
||||
|
||||
it('should pass config when provided', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.post('/test', null, { params: { id: 1 } })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', null, { params: { id: 1 } })
|
||||
})
|
||||
|
||||
it('should reject when response code is not 200', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 500, message: 'Server error' } })
|
||||
await expect(request.post('/test')).rejects.toEqual({ code: 500, message: 'Server error' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('put', () => {
|
||||
it('should call axios.put with url, data, and empty config', async () => {
|
||||
mockPut.mockResolvedValue({ data: { code: 200, data: 'updated' } })
|
||||
const result = await request.put('/test/1', { name: 'bar' })
|
||||
expect(mockPut).toHaveBeenCalledWith('/test/1', { name: 'bar' }, {})
|
||||
expect(result).toEqual({ code: 200, data: 'updated' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('del', () => {
|
||||
it('should call axios.delete with url and params wrapped', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'deleted' } })
|
||||
const result = await request.del('/test/1')
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: {} })
|
||||
expect(result).toEqual({ code: 200, data: 'deleted' })
|
||||
})
|
||||
|
||||
it('should merge params into config spread for axios.delete', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
// del(url, params={reason:'test'}, config={timeout:1000})
|
||||
// => axios.delete(url, { params: { reason:'test' }, timeout: 1000 })
|
||||
await request.del('/test/1', { reason: 'test' }, { timeout: 1000 })
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: { reason: 'test' }, timeout: 1000 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('generic request', () => {
|
||||
it('should dispatch GET with params', async () => {
|
||||
mockGet.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
const result = await request.request('get', '/test', { id: 1 })
|
||||
expect(mockGet).toHaveBeenCalledWith('/test', { params: { id: 1 } })
|
||||
expect(result).toEqual({ code: 200, data: 'ok' })
|
||||
})
|
||||
|
||||
it('should dispatch POST with data', async () => {
|
||||
mockPost.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.request('post', '/test', { name: 'foo' })
|
||||
expect(mockPost).toHaveBeenCalledWith('/test', { name: 'foo' }, {})
|
||||
})
|
||||
|
||||
it('should dispatch DELETE with params', async () => {
|
||||
mockDel.mockResolvedValue({ data: { code: 200, data: 'ok' } })
|
||||
await request.request('delete', '/test/1', null)
|
||||
expect(mockDel).toHaveBeenCalledWith('/test/1', { params: null })
|
||||
})
|
||||
|
||||
it('should throw for unsupported method', () => {
|
||||
expect(() => request.request('patch', '/test', null)).toThrow('请求方法 patch 未实现')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -3,4 +3,12 @@ import request from "@/utils/request";
|
||||
|
||||
export const createFragments = (sessionNum: string, content: string) => {
|
||||
return request.post(`/report-fragments`, {sessionNum, content})
|
||||
}
|
||||
|
||||
export const updateFragments = (id: number, content: string) => {
|
||||
return request.put(`/report-fragments/${id}`, {content})
|
||||
}
|
||||
|
||||
export const getFragmentsBySession = (sessionNum: string) => {
|
||||
return request.get(`/report-fragments/session/${sessionNum}`)
|
||||
}
|
||||
+3
-1
@@ -27,7 +27,9 @@ a:hover {
|
||||
}
|
||||
|
||||
.surface-card {
|
||||
background: var(--surface-strong);
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid var(--border-soft);
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow-soft);
|
||||
|
||||
@@ -3,6 +3,8 @@ import { computed, onMounted, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { getReportDetail, getFragmentDetail, getTaskReview, type ReviewFeedItem } from "@/api/review";
|
||||
import { getSessionDetail } from "@/api/studySessions";
|
||||
import { updateFragments } from "@/api/reportFragments";
|
||||
import { ElMessage } from "element-plus";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -15,6 +17,11 @@ const content = ref("");
|
||||
const sourceTypeLabel = ref("");
|
||||
const taskNum = ref("");
|
||||
|
||||
// 编辑状态
|
||||
const isEditing = ref(false);
|
||||
const editContent = ref("");
|
||||
const saving = ref(false);
|
||||
|
||||
// 当前会话信息
|
||||
const sessionInfo = ref<{
|
||||
taskName: string;
|
||||
@@ -114,6 +121,42 @@ const goToDetail = (type: string, id: number) => {
|
||||
router.push(`/review/detail/${type}/${id}`);
|
||||
};
|
||||
|
||||
const enterEdit = () => {
|
||||
editContent.value = content.value;
|
||||
isEditing.value = true;
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
isEditing.value = false;
|
||||
editContent.value = "";
|
||||
};
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editContent.value.trim()) {
|
||||
ElMessage.warning("内容不能为空");
|
||||
return;
|
||||
}
|
||||
if (editContent.value === content.value) {
|
||||
isEditing.value = false;
|
||||
return;
|
||||
}
|
||||
saving.value = true;
|
||||
try {
|
||||
const res = await updateFragments(contentId.value, editContent.value);
|
||||
if (res?.code === 200) {
|
||||
content.value = editContent.value;
|
||||
isEditing.value = false;
|
||||
ElMessage.success("保存成功");
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loadDetail();
|
||||
});
|
||||
@@ -137,14 +180,38 @@ onMounted(() => {
|
||||
<span v-if="sessionInfo?.startTime" class="meta-time">
|
||||
学习时间:{{ sessionInfo.startTime?.replace("T", " ")?.substring(0, 16) }}
|
||||
</span>
|
||||
<el-button
|
||||
v-if="contentType === 'fragment' && !isEditing"
|
||||
type="primary"
|
||||
size="small"
|
||||
@click="enterEdit"
|
||||
>
|
||||
编辑
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<div class="content-body" v-if="content">
|
||||
<p v-for="(line, idx) in content.split('\n')" :key="idx">
|
||||
{{ line || " " }}
|
||||
</p>
|
||||
<!-- 编辑模式 -->
|
||||
<div v-if="isEditing" class="edit-area">
|
||||
<el-input
|
||||
v-model="editContent"
|
||||
type="textarea"
|
||||
:rows="6"
|
||||
placeholder="请输入学习内容"
|
||||
/>
|
||||
<div class="edit-actions">
|
||||
<el-button @click="cancelEdit">取消</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveEdit">保存</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="empty-content">暂无内容</div>
|
||||
<!-- 只读模式 -->
|
||||
<template v-else>
|
||||
<div class="content-body" v-if="content">
|
||||
<p v-for="(line, idx) in content.split('\n')" :key="idx">
|
||||
{{ line || " " }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-else class="empty-content">暂无内容</div>
|
||||
</template>
|
||||
</article>
|
||||
|
||||
<!-- 该任务下的所有学习记录 -->
|
||||
@@ -176,13 +243,13 @@ onMounted(() => {
|
||||
|
||||
<div class="session-fragments" v-if="session.fragments.length > 0">
|
||||
<span
|
||||
v-for="f in session.fragments"
|
||||
v-for="(f, idx) in session.fragments"
|
||||
:key="f.id"
|
||||
class="clickable-text"
|
||||
:class="{ active: contentType === 'fragment' && f.id === contentId }"
|
||||
@click="goToDetail('fragment', f.id)"
|
||||
>
|
||||
<span class="label-tag fragment-tag">残片</span>
|
||||
<span class="label-tag fragment-tag">残片{{ idx + 1 }}</span>
|
||||
{{ f.content.length > 150 ? f.content.substring(0, 150) + "..." : f.content }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -342,4 +409,15 @@ onMounted(() => {
|
||||
color: #b8860b;
|
||||
}
|
||||
|
||||
.edit-area {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import { useTimer } from "@/components/composables/useTimer";
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
startOrContinueStudySession,
|
||||
} from "@/api/studySessions";
|
||||
import { useStudyFragment } from "@/components/composables/fragment";
|
||||
import { getFragmentsBySession, updateFragments } from "@/api/reportFragments";
|
||||
import router from "@/router";
|
||||
|
||||
const {
|
||||
@@ -23,6 +24,16 @@ const {
|
||||
const summaryDialogVisible = ref(false);
|
||||
const summaryContent = ref("");
|
||||
|
||||
// 当前会话碎片列表
|
||||
interface FragmentItem {
|
||||
id: number;
|
||||
content: string;
|
||||
}
|
||||
const fragmentsList = ref<FragmentItem[]>([]);
|
||||
const editingFragmentId = ref<number | null>(null);
|
||||
const editFragmentContent = ref("");
|
||||
const savingFragment = ref(false);
|
||||
|
||||
const route = useRoute();
|
||||
const taskNum = route.params.taskNum as string;
|
||||
|
||||
@@ -157,7 +168,10 @@ const startTimer = async () => {
|
||||
|
||||
const stopTimer = async () => {
|
||||
const res = await pauseSession(taskInfo.value.sessionNum);
|
||||
if (res.code === 200) ElMessage.success("任务暂停");
|
||||
if (res.code === 200) {
|
||||
ElMessage.success("任务暂停");
|
||||
taskInfo.value.sessionState = "PAUSED";
|
||||
}
|
||||
clear();
|
||||
};
|
||||
|
||||
@@ -180,7 +194,11 @@ const endTimer = async (content: string) => {
|
||||
try {
|
||||
const res = await endSession(taskInfo.value.sessionNum, content);
|
||||
if (res.code === 200) {
|
||||
ElMessage.success("任务结束");
|
||||
if (res.message && res.message !== "请求成功") {
|
||||
ElMessage.warning(res.message);
|
||||
} else {
|
||||
ElMessage.success("任务结束");
|
||||
}
|
||||
} else {
|
||||
ElMessage.error(res.message || "结束会话失败");
|
||||
}
|
||||
@@ -213,6 +231,7 @@ const loadTaskSession = async () => {
|
||||
} else {
|
||||
syncDisplay(taskInfo.value.pointerPosition || 25 * 60 * 1000);
|
||||
}
|
||||
loadFragments();
|
||||
} catch (err: any) {
|
||||
ElMessage.error(err.message || "加载任务失败");
|
||||
}
|
||||
@@ -227,6 +246,53 @@ const initPage = async () => {
|
||||
await loadTaskSession();
|
||||
};
|
||||
|
||||
// 碎片列表
|
||||
const loadFragments = async () => {
|
||||
if (!taskInfo.value.sessionNum) return;
|
||||
try {
|
||||
const res = await getFragmentsBySession(taskInfo.value.sessionNum);
|
||||
if (res?.code === 200) {
|
||||
fragmentsList.value = res.data || [];
|
||||
}
|
||||
} catch {
|
||||
// 非关键数据
|
||||
}
|
||||
};
|
||||
|
||||
const startEditFragment = (fragment: FragmentItem) => {
|
||||
editingFragmentId.value = fragment.id;
|
||||
editFragmentContent.value = fragment.content;
|
||||
};
|
||||
|
||||
const cancelEditFragment = () => {
|
||||
editingFragmentId.value = null;
|
||||
editFragmentContent.value = "";
|
||||
};
|
||||
|
||||
const saveEditFragment = async (id: number) => {
|
||||
if (!editFragmentContent.value.trim()) {
|
||||
ElMessage.warning("内容不能为空");
|
||||
return;
|
||||
}
|
||||
savingFragment.value = true;
|
||||
try {
|
||||
const res = await updateFragments(id, editFragmentContent.value);
|
||||
if (res?.code === 200) {
|
||||
const item = fragmentsList.value.find((f) => f.id === id);
|
||||
if (item) item.content = editFragmentContent.value;
|
||||
editingFragmentId.value = null;
|
||||
editFragmentContent.value = "";
|
||||
ElMessage.success("保存成功");
|
||||
} else {
|
||||
ElMessage.error(res?.message || "保存失败");
|
||||
}
|
||||
} catch (e: any) {
|
||||
ElMessage.error(e.message || "请求失败");
|
||||
} finally {
|
||||
savingFragment.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
displayInterval = window.setInterval(() => {
|
||||
nowTimestamp.value = Date.now();
|
||||
@@ -234,6 +300,13 @@ onMounted(() => {
|
||||
initPage();
|
||||
});
|
||||
|
||||
// 碎片创建成功后刷新列表
|
||||
watch(fragmentsDialogVisible, (newVal, oldVal) => {
|
||||
if (oldVal === true && newVal === false) {
|
||||
loadFragments();
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (displayInterval) {
|
||||
clearInterval(displayInterval);
|
||||
@@ -243,6 +316,7 @@ onUnmounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<section class="start-page">
|
||||
<div class="task-info-bar">
|
||||
<el-tag type="success" effect="plain">任务编号:{{ taskInfo.taskNum }}</el-tag>
|
||||
@@ -298,6 +372,34 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<!-- 当前会话学习残片 -->
|
||||
<article class="surface-card fragments-card" v-if="fragmentsList.length > 0">
|
||||
<h3>当前会话学习残片</h3>
|
||||
<div
|
||||
v-for="(fragment, index) in fragmentsList"
|
||||
:key="fragment.id"
|
||||
class="fragment-item"
|
||||
>
|
||||
<span class="fragment-index">{{ index + 1 }}</span>
|
||||
<template v-if="editingFragmentId === fragment.id">
|
||||
<el-input
|
||||
v-model="editFragmentContent"
|
||||
type="textarea"
|
||||
:rows="3"
|
||||
placeholder="请输入学习内容"
|
||||
/>
|
||||
<div class="fragment-edit-actions">
|
||||
<el-button size="small" @click="cancelEditFragment">取消</el-button>
|
||||
<el-button size="small" type="primary" :loading="savingFragment" @click="saveEditFragment(fragment.id)">保存</el-button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="fragment-content">{{ fragment.content }}</span>
|
||||
<el-button size="small" @click="startEditFragment(fragment)">编辑</el-button>
|
||||
</template>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="fragmentsDialogVisible" title="生成学习残片" width="520px">
|
||||
@@ -325,6 +427,7 @@ onUnmounted(() => {
|
||||
<el-button type="success" @click="endTimer(summaryContent)">确认结束</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
@@ -425,6 +528,56 @@ onUnmounted(() => {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fragments-card {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.fragments-card h3 {
|
||||
margin: 0 0 14px;
|
||||
color: var(--green-900);
|
||||
}
|
||||
|
||||
.fragment-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 10px 0;
|
||||
border-bottom: 1px solid var(--border-soft);
|
||||
}
|
||||
|
||||
.fragment-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.fragment-index {
|
||||
flex-shrink: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
background: var(--green-600);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.fragment-content {
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-primary);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.fragment-edit-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.session-grid {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
@@ -25,34 +25,37 @@ export const useStudyFragment = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const confirmGenerateFragment = async (sessionNum: string) => {
|
||||
const confirmGenerateFragment = async (sessionNum: string): Promise<boolean> => {
|
||||
if (!fragmentContent.value.trim()) {
|
||||
ElMessage.warning('请输入学习内容!');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
})
|
||||
.then(async () => {
|
||||
try {
|
||||
const res = await createFragments(sessionNum, fragmentContent.value);
|
||||
|
||||
if (res.code === 200) {
|
||||
ElMessage.success('学习残片生成成功!');
|
||||
fragmentsDialogVisible.value = false;
|
||||
} else {
|
||||
ElMessage.error(res.message || '生成学习残片失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '请求失败');
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
ElMessage.info('已取消生成');
|
||||
try {
|
||||
await ElMessageBox.confirm('确定要生成学习残片吗?', '提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'info',
|
||||
});
|
||||
} catch {
|
||||
ElMessage.info('已取消生成');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await createFragments(sessionNum, fragmentContent.value);
|
||||
if (res.code === 200) {
|
||||
ElMessage.success('学习残片生成成功!');
|
||||
fragmentsDialogVisible.value = false;
|
||||
return true;
|
||||
} else {
|
||||
ElMessage.error(res.message || '生成学习残片失败');
|
||||
return false;
|
||||
}
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error.message || '请求失败');
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
|
||||
import { defineConfig } from 'vite'
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// https://vite.dev/config/
|
||||
@@ -23,5 +23,11 @@ export default defineConfig({
|
||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./src/__tests__/setup.ts'],
|
||||
include: ['src/**/*.spec.ts', 'src/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user