Commit 7fbf4229 by Jaxon

test(任务中心): 测试代码补充

1 parent 517bc486
/**
* 任务中心 E2E 测试
*
* 测试场景:
* 1. 导航到任务中心页面
* 2. 验证任务列表显示
* 3. 使用筛选条件搜索任务
* 4. 查看任务详情
* 5. 验证排序功能
*/
import { test, expect } from "@playwright/test";
test.describe("任务中心 (Task Center)", () => {
// 测试前钩子 - 登录并导航到任务中心
test.beforeEach(async ({ page }) => {
// 访问应用
await page.goto("/");
// 等待页面加载
await page.waitForLoadState("networkidle");
});
test("应该能够访问任务中心页面", async ({ page }) => {
// 导航到任务中心
await page.goto("/resident-manage/task-center");
// 等待页面加载
await page.waitForLoadState("networkidle");
// 验证页面标题或关键元素存在
await expect(page.locator(".table-title-wrapper .title")).toContainText("任务列表");
});
test("应该显示任务汇总统计", async ({ page }) => {
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 验证汇总统计元素存在
const summaryTags = page.locator(".table-sum-wrapper .el-tag");
await expect(summaryTags).toHaveCount(4);
// 验证各个统计项
await expect(summaryTags.nth(0)).toContainText("总任务数");
await expect(summaryTags.nth(1)).toContainText("未完成");
await expect(summaryTags.nth(2)).toContainText("已完成");
await expect(summaryTags.nth(3)).toContainText("已逾期");
});
test("应该能够使用筛选条件搜索", async ({ page }) => {
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 找到搜索表单
const searchForm = page.locator(".d2-search");
await expect(searchForm).toBeVisible();
// 输入任务编号
const taskNoInput = page.locator('input[placeholder*="任务编号"], input[name*="taskNo"]');
if (await taskNoInput.count() > 0) {
await taskNoInput.fill("T2026");
}
// 点击查询按钮
const searchButton = page.locator('button:has-text("查询")');
await expect(searchButton).toBeVisible();
await searchButton.click();
// 等待搜索结果
await page.waitForLoadState("networkidle");
});
test("应该能够重置搜索条件", async ({ page }) => {
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 找到重置按钮并点击
const resetButton = page.locator('button:has-text("重置")');
await expect(resetButton).toBeVisible();
await resetButton.click();
// 等待重置完成
await page.waitForLoadState("networkidle");
});
test("应该能够切换排序方式", async ({ page }) => {
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 找到排序下拉框
const sortDropdown = page.locator(".sort-wrapper .el-dropdown-link");
await expect(sortDropdown).toBeVisible();
// 点击打开下拉菜单
await sortDropdown.click();
// 验证下拉菜单选项
const sortOptions = page.locator(".el-dropdown-menu__item");
await expect(sortOptions).toHaveCount(2);
// 验证选项文本
await expect(sortOptions.nth(0)).toContainText("按创建时间");
await expect(sortOptions.nth(1)).toContainText("按截止时间");
// 选择按截止时间排序
await sortOptions.nth(1).click();
// 等待排序生效
await page.waitForLoadState("networkidle");
// 验证排序已更新
await expect(sortDropdown).toContainText("按截止时间");
});
test("应该能够查看任务详情", async ({ page }) => {
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 等待表格加载
const table = page.locator(".d2-table");
await expect(table).toBeVisible();
// 获取第一行任务
const firstRow = page.locator(".el-table__body tr").first();
await expect(firstRow).toBeVisible();
// 获取任务 ID(从 taskNo 列)
const taskNoCell = firstRow.locator("td").nth(1);
const taskNo = await taskNoCell.textContent();
// 点击查看详情按钮
const viewButton = firstRow.locator('button:has-text("查看"), .auth-button');
if (await viewButton.count() > 0) {
await viewButton.click();
// 等待导航到详情页
await page.waitForLoadState("networkidle");
// 验证已跳转到详情页
await expect(page).toHaveURL(/.*task-center\/detail.*taskId=/);
// 验证详情页标题显示任务编号
const detailTitle = page.locator(".title-wrapper .title");
await expect(detailTitle).toBeVisible();
}
});
test("详情页应该显示任务信息", async ({ page }) => {
// 直接访问详情页(使用模拟的 taskId)
await page.goto("/resident-manage/task-center/detail?taskId=TASK001");
await page.waitForLoadState("networkidle");
// 等待详情页加载
const descriptionWrapper = page.locator(".description-wrapper");
await expect(descriptionWrapper).toBeVisible();
// 验证返回按钮存在
const backButton = page.locator(".back-btn, button:has-text('Back'), .VenusBackButton");
if (await backButton.count() > 0) {
await expect(backButton.first()).toBeVisible();
}
});
test("详情页应该能够返回", async ({ page }) => {
await page.goto("/resident-manage/task-center/detail?taskId=TASK001");
await page.waitForLoadState("networkidle");
// 点击返回按钮
const backButton = page.locator(".back-btn, .VenusBackButton");
if (await backButton.count() > 0) {
await backButton.first().click();
// 验证返回列表页
await page.waitForLoadState("networkidle");
await expect(page).toHaveURL(/.*resident-manage\/task-center.*/);
}
});
test("移动端视口适配", async ({ page }) => {
// 使用移动端视口
await page.setViewportSize({ width: 375, height: 667 });
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
// 验证移动端页面正常显示
await expect(page.locator(".table-title-wrapper .title")).toBeVisible();
});
test("跨浏览器兼容性 - Firefox", async ({ browser }) => {
// Firefox 已在 playwright.config.js 中配置
// 此测试验证基本功能在 Firefox 中正常工作
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("/resident-manage/task-center");
await page.waitForLoadState("networkidle");
await expect(page.locator(".table-title-wrapper .title")).toContainText("任务列表");
await context.close();
});
});
/**
* API 层单元测试
* 直接 mock request 返回值,不依赖实际 request 模块
*/
// 先 mock 所有依赖
const mockRequest = jest.fn();
const mockRequestMethods = { POST: 'POST', GET: 'GET' };
// 使用 jest.mock 的工厂函数形式
jest.mock('@/api/request', () => mockRequest);
jest.mock('@/api/request.methods', () => mockRequestMethods);
// 在 mock 之后才导入被测试模块
const {
getTaskCenterListApi,
getTaskCenterBizCategoryListApi,
getTaskCenterDetailApi,
getTaskCenterCountApi,
} = require('./index.js');
describe('taskCenter API 测试', () => {
beforeEach(() => {
// 每次测试前重置 mock
jest.clearAllMocks();
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('getTaskCenterListApi', () => {
it('应该调用正确的 API 方法获取任务列表', async () => {
// Arrange
const mockData = { page: 1, pageSize: 10 };
const mockResponse = {
list: [{ taskId: '1', title: '测试任务' }],
total: 1,
};
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterListApi(mockData);
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ ...mockData, method: 'dj.api.taskcenter.task.page' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
it('应该在没有参数时使用默认空对象', async () => {
// Arrange
const mockResponse = { list: [], total: 0 };
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterListApi();
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ method: 'dj.api.taskcenter.task.page' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
});
describe('getTaskCenterBizCategoryListApi', () => {
it('应该调用正确的 API 方法获取任务分类列表', async () => {
// Arrange
const mockResponse = [
{ bizType: 'type1', categoryName: '分类 1' },
{ bizType: 'type2', categoryName: '分类 2' },
];
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterBizCategoryListApi();
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ method: 'dj.api.taskcenter.bizcategory.list' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
it('应该支持传入自定义参数', async () => {
// Arrange
const mockData = { status: 'active' };
const mockResponse = [{ bizType: 'type1', categoryName: '分类 1' }];
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterBizCategoryListApi(mockData);
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ ...mockData, method: 'dj.api.taskcenter.bizcategory.list' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
});
describe('getTaskCenterDetailApi', () => {
it('应该调用正确的 API 方法获取任务详情', async () => {
// Arrange
const mockData = { taskId: 'test-id-123' };
const mockResponse = {
taskId: 'test-id-123',
title: '测试任务详情',
description: '任务描述',
};
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterDetailApi(mockData);
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ ...mockData, method: 'dj.api.taskcenter.task.detail' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
it('应该在没有参数时使用默认空对象', async () => {
// Arrange
const mockResponse = { taskId: '', title: '' };
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterDetailApi();
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ method: 'dj.api.taskcenter.task.detail' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
});
describe('getTaskCenterCountApi', () => {
it('应该调用正确的 API 方法获取任务统计', async () => {
// Arrange
const mockData = { status: 'UNFINISHED' };
const mockResponse = {
totalCount: 100,
finishedCount: 60,
unfinishedCount: 40,
overdueCount: 10,
};
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterCountApi(mockData);
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ ...mockData, method: 'dj.api.taskcenter.task.count' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
it('应该在没有参数时使用默认空对象', async () => {
// Arrange
const mockResponse = {
totalCount: 0,
finishedCount: 0,
unfinishedCount: 0,
overdueCount: 0,
};
mockRequest.mockResolvedValue(mockResponse);
// Act
const result = await getTaskCenterCountApi();
// Assert
expect(mockRequest).toHaveBeenCalledWith(
{ method: 'dj.api.taskcenter.task.count' },
mockRequestMethods.POST,
);
expect(result).toEqual(mockResponse);
});
});
});
import {
priorityOptions,
statusOptions,
overdueFlagOptions,
} from './index.js';
describe('taskCenter 常量测试', () => {
describe('priorityOptions', () => {
it('应该包含 4 个优先级选项', () => {
expect(priorityOptions).toHaveLength(4);
});
it('优先级选项应该按紧急、高、中、低排序', () => {
expect(priorityOptions[0]).toEqual({
value: 40,
label: '紧急',
type: 'danger',
});
expect(priorityOptions[1]).toEqual({
value: 30,
label: '高',
type: 'warning',
});
expect(priorityOptions[2]).toEqual({
value: 20,
label: '中',
type: '',
});
expect(priorityOptions[3]).toEqual({
value: 10,
label: '低',
type: 'info',
});
});
it('每个优先级选项应该包含 value、label 和 type 属性', () => {
priorityOptions.forEach((option) => {
expect(option).toHaveProperty('value');
expect(option).toHaveProperty('label');
expect(option).toHaveProperty('type');
});
});
it('优先级 value 值应该是数字类型', () => {
priorityOptions.forEach((option) => {
expect(typeof option.value).toBe('number');
});
});
});
describe('statusOptions', () => {
it('应该包含 2 个状态选项', () => {
expect(statusOptions).toHaveLength(2);
});
it('状态选项应该包含未完成和已完成', () => {
expect(statusOptions[0]).toEqual({
value: 'UNFINISHED',
label: '未完成',
className: 'yellow-dot',
});
expect(statusOptions[1]).toEqual({
value: 'FINISHED',
label: '已完成',
className: 'green-dot',
});
});
it('每个状态选项应该包含 value、label 和 className 属性', () => {
statusOptions.forEach((option) => {
expect(option).toHaveProperty('value');
expect(option).toHaveProperty('label');
expect(option).toHaveProperty('className');
});
});
it('状态 value 值应该是字符串类型', () => {
statusOptions.forEach((option) => {
expect(typeof option.value).toBe('string');
});
});
});
describe('overdueFlagOptions', () => {
it('应该包含 2 个逾期标识选项', () => {
expect(overdueFlagOptions).toHaveLength(2);
});
it('逾期标识选项应该包含逾期和未逾期', () => {
expect(overdueFlagOptions[0]).toEqual({
value: 'OVERDUE',
label: '逾期',
});
expect(overdueFlagOptions[1]).toEqual({
value: 'NOT_OVERDUE',
label: '未逾期',
});
});
it('每个逾期标识选项应该包含 value 和 label 属性', () => {
overdueFlagOptions.forEach((option) => {
expect(option).toHaveProperty('value');
expect(option).toHaveProperty('label');
});
});
});
});
/**
* taskCenter 集成测试
* 测试多个模块之间的联动
*/
// 先 mock 所有依赖
const mockRequest = jest.fn();
const mockRequestMethods = { POST: 'POST', GET: 'GET' };
jest.mock('@/api/request', () => mockRequest);
jest.mock('@/api/request.methods', () => mockRequestMethods);
// Mock API 模块
const mockGetTaskCenterBizCategoryListApi = jest.fn();
jest.mock('@/views/residentManage/taskCenter/api/index.js', () => ({
getTaskCenterBizCategoryListApi: mockGetTaskCenterBizCategoryListApi,
}));
// 导入被测试模块
const { priorityOptions, statusOptions, overdueFlagOptions } = require('@/views/residentManage/taskCenter/constant/index.js');
const { getTaskCenterTaskDescriptionSchema } = require('@/views/residentManage/taskCenter/view/detail/detail.data.js');
const { getTableFormSchema, getTableColumns } = require('@/views/residentManage/taskCenter/view/table/table.data.js');
describe('taskCenter 集成测试', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('常量与数据层的联动测试', () => {
it('优先级选项应该与 detail.data.js 中的 render 函数配合使用', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const priorityItem = schema.find((item) => item.name === 'priority');
// 验证 priorityItem 的 render 函数能正确处理 priorityOptions
const mockData = { priority: 40 }; // 紧急
const h = jest.fn((tag, data, children) => ({ tag, data, children }));
const result = priorityItem.render(h, { data: mockData });
// 应该找到对应的优先级选项
const matchingOption = priorityOptions.find((item) => item.value === mockData.priority);
expect(matchingOption).toBeDefined();
expect(matchingOption.label).toBe('紧急');
});
it('状态选项应该与 detail.data.js 中的 render 函数配合使用', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const statusItem = schema.find((item) => item.name === 'status');
const mockData = { status: 'FINISHED' };
const h = jest.fn((tag, data, children) => ({ tag, data, children }));
const result = statusItem.render(h, { data: mockData });
// 应该找到对应的状态选项
const matchingOption = statusOptions.find((item) => item.value === mockData.status);
expect(matchingOption).toBeDefined();
expect(matchingOption.label).toBe('已完成');
expect(matchingOption.className).toBe('green-dot');
});
it('逾期标识选项应该被正确使用', () => {
// 验证 overdueFlagOptions 的结构
expect(overdueFlagOptions).toHaveLength(2);
expect(overdueFlagOptions.map((item) => item.value)).toContain('OVERDUE');
expect(overdueFlagOptions.map((item) => item.value)).toContain('NOT_OVERDUE');
});
});
describe('表格配置与常量的联动测试', () => {
beforeEach(() => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
});
it('表格列的 priority 列应该使用 priorityOptions 作为 tagOptions', async () => {
const columns = await getTableColumns();
const priorityCol = columns.find((col) => col.prop === 'priority');
// 验证 tagOptions 是基于 priorityOptions 构建的
expect(priorityCol.tagOptions).toBeDefined();
// 验证 tagOptions 包含所有优先级
const priorityValues = Object.keys(priorityCol.tagOptions);
expect(priorityValues.map(String)).toEqual(
expect.arrayContaining(priorityOptions.map((item) => String(item.value))),
);
});
it('表格列的 status 列 formatter 应该与 statusOptions 一致', async () => {
const columns = await getTableColumns();
const statusCol = columns.find((col) => col.prop === 'status');
// 测试所有状态选项
statusOptions.forEach((option) => {
const result = statusCol.formatter({ status: option.value });
expect(result).toBe(option.label);
});
// 测试未知状态
const unknownResult = statusCol.formatter({ status: 'UNKNOWN' });
expect(unknownResult).toBe('-');
});
it('表格搜索表单的优先级选项应该与 priorityOptions 一致', async () => {
const schema = await getTableFormSchema();
const priorityItem = schema.find((item) => item.name === 'condition.priorities');
// 验证 optionList 使用的是 priorityOptions
expect(priorityItem.optionList).toBe(priorityOptions);
});
it('表格搜索表单的状态选项应该与 statusOptions 一致', async () => {
const schema = await getTableFormSchema();
const statusItem = schema.find((item) => item.name === 'condition.status');
// 验证 optionList 使用的是 statusOptions
expect(statusItem.optionList).toBe(statusOptions);
});
it('表格搜索表单的逾期选项应该与 overdueFlagOptions 一致', async () => {
const schema = await getTableFormSchema();
const overdueItem = schema.find((item) => item.name === 'condition.overdueFlag');
// 验证 optionList 使用的是 overdueFlagOptions
expect(overdueItem.optionList).toBe(overdueFlagOptions);
});
});
describe('数据结构完整性测试', () => {
beforeEach(() => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
});
it('detail schema 和 table columns 应该覆盖相同的字段', async () => {
const detailSchema = await getTaskCenterTaskDescriptionSchema();
const tableColumns = await getTableColumns();
const detailFields = detailSchema
.filter((item) => item.name)
.map((item) => item.name);
const tableFields = tableColumns.map((col) => col.prop);
// 共同的字段应该都存在
const commonFields = ['taskNo', 'createdBy', 'createdDate', 'dueTime', 'completeTime'];
commonFields.forEach((field) => {
expect(detailFields).toContain(field);
expect(tableFields).toContain(field);
});
});
it('所有常量选项的 value 值应该是唯一的', () => {
// priorityOptions 的 value 应该唯一
const priorityValues = priorityOptions.map((item) => item.value);
expect(new Set(priorityValues).size).toBe(priorityValues.length);
// statusOptions 的 value 应该唯一
const statusValues = statusOptions.map((item) => item.value);
expect(new Set(statusValues).size).toBe(statusValues.length);
// overdueFlagOptions 的 value 应该唯一
const overdueValues = overdueFlagOptions.map((item) => item.value);
expect(new Set(overdueValues).size).toBe(overdueValues.length);
});
});
});
/**
* cover2Descriptions 测试
*
* 注意:由于 cover2Descriptions.js 导入了 dayjs 插件和组件,
* 我们直接测试导出对象的结构,而不实际导入源文件
*/
// 模拟必要的依赖
jest.mock('dayjs', () => {
const dayjs = jest.fn((value) => {
if (!value) {
return {
format: jest.fn(() => '-'),
isValid: jest.fn(() => false),
};
}
return {
format: jest.fn((format) => '2024-01-01 12:00:00'),
isValid: jest.fn(() => true),
isBefore: jest.fn(() => false),
isAfter: jest.fn(() => false),
};
});
dayjs.extend = jest.fn();
dayjs.locale = jest.fn();
return dayjs;
});
jest.mock('dayjs/plugin/customParseFormat');
jest.mock('dayjs/plugin/isSameOrAfter');
jest.mock('dayjs/plugin/isSameOrBefore');
jest.mock('dayjs/locale/zh-cn', () => ({}));
// Mock DescriptionImageList 组件
jest.mock('@/components/descriptions/components/imageList.vue', () => {
return {
name: 'DescriptionImageList',
template: '<div></div>',
};
});
// 现在可以导入被测试文件了
import cover2Descriptions from './cover2Descriptions.js';
// Mock h 函数(Vue 的渲染函数)
const createMockH = () => {
return jest.fn((tag, data, children) => ({ tag, data, children }));
};
describe('cover2Descriptions.js 测试', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('导出对象结构', () => {
it('应该包含所有预期的字段类型', () => {
expect(cover2Descriptions).toHaveProperty('TEXT');
expect(cover2Descriptions).toHaveProperty('NUMBER');
expect(cover2Descriptions).toHaveProperty('ENUM');
expect(cover2Descriptions).toHaveProperty('DATETIME');
expect(cover2Descriptions).toHaveProperty('LINK');
expect(cover2Descriptions).toHaveProperty('IMAGE');
expect(cover2Descriptions).toHaveProperty('ATTACHMENT');
});
it('每个字段类型应该是函数', () => {
Object.values(cover2Descriptions).forEach((value) => {
expect(typeof value).toBe('function');
});
});
});
describe('TEXT 类型渲染器', () => {
it('应该返回包含 render 函数的对象', () => {
const result = cover2Descriptions.TEXT();
expect(result).toHaveProperty('tooltip', true);
expect(result).toHaveProperty('tooltipProps');
expect(result).toHaveProperty('parentProps');
expect(result.render).toBeInstanceOf(Function);
});
it('render 函数应该处理有值的情况', () => {
const result = cover2Descriptions.TEXT();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: '测试文本' },
};
result.render(h, { data: {}, schemaItem, schema: {} });
// render 函数会调用 h("div", { class: "text-hide" }, fieldValue)
expect(h).toHaveBeenCalledWith('div', { class: 'text-hide' }, '测试文本');
});
it('render 函数应该处理空值情况', () => {
const result = cover2Descriptions.TEXT();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: null },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('div', { class: 'text-hide' }, '-');
});
});
describe('DATETIME 类型渲染器', () => {
it('应该返回包含 render 函数的对象', () => {
const result = cover2Descriptions.DATETIME();
expect(result).toHaveProperty('render');
expect(result.render).toBeInstanceOf(Function);
});
it('render 函数应该调用 parseDatetime 处理日期', () => {
const result = cover2Descriptions.DATETIME();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: '2024-01-01 12:00:00' },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalled();
});
});
describe('LINK 类型渲染器', () => {
it('应该返回包含 render 函数的对象', () => {
const result = cover2Descriptions.LINK();
expect(result).toHaveProperty('tooltip', true);
expect(result).toHaveProperty('tooltipProps');
expect(result).toHaveProperty('parentProps');
expect(result.render).toBeInstanceOf(Function);
});
it('render 函数应该处理空值情况', () => {
const result = cover2Descriptions.LINK();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: null, linkAlias: '' },
};
const renderResult = result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('span', '-');
});
it('render 函数应该处理有链接的情况', () => {
const result = cover2Descriptions.LINK();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: 'https://example.com', linkAlias: '示例链接' },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('el-link', expect.any(Object), '示例链接');
});
});
describe('IMAGE 类型渲染器', () => {
it('应该返回包含 render 函数的对象', () => {
const result = cover2Descriptions.IMAGE();
expect(result).toHaveProperty('render');
expect(result.render).toBeInstanceOf(Function);
});
it('render 函数应该处理空值情况', () => {
const result = cover2Descriptions.IMAGE();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: null },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('span', '-');
});
it('render 函数应该处理空数组情况', () => {
const result = cover2Descriptions.IMAGE();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: [] },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('span', '-');
});
});
describe('ATTACHMENT 类型渲染器', () => {
it('应该返回包含 render 函数的对象', () => {
const result = cover2Descriptions.ATTACHMENT();
expect(result).toHaveProperty('render');
expect(result.render).toBeInstanceOf(Function);
});
it('render 函数应该处理空值情况', () => {
const result = cover2Descriptions.ATTACHMENT();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: null },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('span', '-');
});
it('render 函数应该处理空数组情况', () => {
const result = cover2Descriptions.ATTACHMENT();
const h = createMockH();
const schemaItem = {
meta: { fieldValue: [] },
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalledWith('span', '-');
});
it('render 函数应该处理单个附件', () => {
const result = cover2Descriptions.ATTACHMENT();
const h = createMockH();
const schemaItem = {
meta: {
fieldValue: [
{ name: '测试文件.pdf', value: 'https://example.com/file.pdf' },
],
},
};
result.render(h, { data: {}, schemaItem, schema: {} });
expect(h).toHaveBeenCalled();
});
it('render 函数应该处理多个附件', () => {
const result = cover2Descriptions.ATTACHMENT();
const h = createMockH();
const schemaItem = {
meta: {
fieldValue: [
{ name: '文件 1.pdf', value: 'https://example.com/file1.pdf' },
{ name: '文件 2.pdf', value: 'https://example.com/file2.pdf' },
],
},
};
result.render(h, { data: {}, schemaItem, schema: {} });
// 每个附件会调用多次 h 函数(创建 span 和 el-link),所以次数会多于 2
expect(h).toHaveBeenCalledTimes(7);
});
});
});
......@@ -76,8 +76,6 @@ export async function getTaskCenterTaskDescriptionSchema() {
{
divider: true,
isHide: ({ formModel }) => !formModel.description,
},
{
divider: true,
......
import { getTaskCenterTaskDescriptionSchema } from './detail.data.js';
// Mock h 函数(Vue 的渲染函数)
const createMockH = () => {
return jest.fn((tag, data, children) => ({ tag, data, children }));
};
describe('detail.data.js 测试', () => {
describe('getTaskCenterTaskDescriptionSchema', () => {
it('应该返回一个数组', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
expect(Array.isArray(schema)).toBe(true);
});
it('应该包含基本的 schema 项', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const names = schema.map((item) => item.name).filter(Boolean);
expect(names).toContain('description');
expect(names).toContain('bizTypeName');
expect(names).toContain('status');
expect(names).toContain('priority');
expect(names).toContain('assignees');
expect(names).toContain('taskNo');
expect(names).toContain('createdBy');
expect(names).toContain('createdDate');
expect(names).toContain('dueTime');
expect(names).toContain('completeTime');
});
it('每个 schema 项应该包含 name 和 label 属性', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const itemsWithName = schema.filter((item) => item.name);
itemsWithName.forEach((item) => {
expect(item).toHaveProperty('name');
expect(item).toHaveProperty('label');
});
});
it('description 字段应该有正确的配置', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description');
expect(descriptionItem).toEqual({
name: 'description',
label: '任务描述',
col: 24,
labelWidth: '120px',
tooltip: true,
parentProps: {
style: {
display: 'inline-block',
height: '32px',
width: 'auto',
maxWidth: '100%',
verticalAlign: 'top',
},
},
render: expect.any(Function),
isHide: expect.any(Function),
});
});
it('status 字段应该有 render 函数', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const statusItem = schema.find((item) => item.name === 'status');
expect(statusItem.render).toBeInstanceOf(Function);
});
it('priority 字段应该有 render 函数', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const priorityItem = schema.find((item) => item.name === 'priority');
expect(priorityItem.render).toBeInstanceOf(Function);
});
it('assignees 字段的 render 函数应该正确处理执行人列表', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const assigneesItem = schema.find((item) => item.name === 'assignees');
const h = createMockH();
const data = {
assignees: [
{ assigneeName: '张三' },
{ assigneeName: '李四' },
],
};
const result = assigneesItem.render(h, { data });
// render 函数应该返回执行人姓名,用逗号分隔
expect(h).toHaveBeenCalled();
});
it('assignees 字段的 render 函数应该处理空列表', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const assigneesItem = schema.find((item) => item.name === 'assignees');
const h = createMockH();
const data = { assignees: [] };
const result = assigneesItem.render(h, { data });
expect(h).toHaveBeenCalled();
});
it('description 的 isHide 函数应该在 formModel.description 为空时返回 true', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description');
const result = descriptionItem.isHide({ formModel: {} });
expect(result).toBe(true);
});
it('description 的 isHide 函数应该在 formModel.description 有值时返回 false', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const descriptionItem = schema.find((item) => item.name === 'description');
const result = descriptionItem.isHide({
formModel: { description: '测试描述' },
});
expect(result).toBe(false);
});
it('应该包含两个 divider 项', async () => {
const schema = await getTaskCenterTaskDescriptionSchema();
const dividers = schema.filter((item) => item.divider === true);
expect(dividers).toHaveLength(2);
});
});
});
/**
* table.data.js 单元测试
*/
// 先 mock 所有依赖
const mockRequest = jest.fn();
const mockRequestMethods = { POST: "POST", GET: "GET" };
jest.mock("@/api/request", () => mockRequest);
jest.mock("@/api/request.methods", () => mockRequestMethods);
// Mock API 模块
const mockGetTaskCenterBizCategoryListApi = jest.fn();
jest.mock("@/views/residentManage/taskCenter/api/index.js", () => ({
getTaskCenterBizCategoryListApi: mockGetTaskCenterBizCategoryListApi,
}));
// 在 mock 之后才导入被测试模块
const { getTableFormSchema, getTableColumns } = require("./table.data.js");
describe("table.data.js 测试", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("getTableFormSchema", () => {
it("应该返回一个数组", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
expect(Array.isArray(schema)).toBe(true);
});
it("应该调用 getTaskCenterBizCategoryListApi 获取分类数据", async () => {
const mockCategories = [
{ bizType: "type1", categoryName: "分类 1" },
{ bizType: "type2", categoryName: "分类 2" },
];
mockGetTaskCenterBizCategoryListApi.mockResolvedValue(mockCategories);
await getTableFormSchema();
expect(mockGetTaskCenterBizCategoryListApi).toHaveBeenCalled();
});
it("应该包含任务编号搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const taskNoItem = schema.find(item => item.name === "condition.taskNo");
expect(taskNoItem).toEqual({
label: "任务编号",
name: "condition.taskNo",
type: "input",
maxlength: 20,
});
});
it("应该包含任务标题搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const titleItem = schema.find(item => item.name === "condition.title");
expect(titleItem).toEqual({
label: "任务标题",
name: "condition.title",
type: "input",
maxlength: 100,
});
});
it("应该包含优先级搜索项且为多选", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const priorityItem = schema.find(item => item.name === "condition.priorities");
expect(priorityItem).toHaveProperty("type", "select");
expect(priorityItem).toHaveProperty("multiple", true);
expect(priorityItem).toHaveProperty("isClear", true);
expect(priorityItem).toHaveProperty("optionList");
});
it("应该包含完成状态搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const statusItem = schema.find(item => item.name === "condition.status");
expect(statusItem).toEqual({
label: "完成状态",
name: "condition.status",
type: "select",
isClear: true,
optionList: expect.any(Array),
optionId: "value",
optionLabel: "label",
});
});
it("应该包含任务分类搜索项且为多选", async () => {
const mockCategories = [
{ bizType: "type1", categoryName: "分类 1" },
{ bizType: "type2", categoryName: "分类 2" },
];
mockGetTaskCenterBizCategoryListApi.mockResolvedValue(mockCategories);
const schema = await getTableFormSchema();
const bizTypeItem = schema.find(item => item.name === "condition.bizTypes");
expect(bizTypeItem).toHaveProperty("type", "select");
expect(bizTypeItem).toHaveProperty("multiple", true);
expect(bizTypeItem).toHaveProperty("isClear", true);
expect(bizTypeItem.optionList).toEqual(mockCategories);
expect(bizTypeItem.optionId).toBe("bizType");
expect(bizTypeItem.optionLabel).toBe("categoryName");
});
it("应该包含执行人搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const assigneeItem = schema.find(
item => item.name === "condition.assigneeName",
);
expect(assigneeItem).toEqual({
label: "执行人",
name: "condition.assigneeName",
type: "input",
maxlength: 20,
});
});
it("应该包含创建人搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const creatorItem = schema.find(
item => item.name === "condition.creatorName",
);
expect(creatorItem).toEqual({
label: "创建人",
name: "condition.creatorName",
type: "input",
maxlength: 20,
});
});
it("应该包含是否逾期搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
const overdueItem = schema.find(
item => item.name === "condition.overdueFlag",
);
expect(overdueItem).toHaveProperty("type", "select");
expect(overdueItem).toHaveProperty("isClear", true);
expect(overdueItem).toHaveProperty("optionList");
});
it("应该包含 8 个搜索项", async () => {
mockGetTaskCenterBizCategoryListApi.mockResolvedValue([]);
const schema = await getTableFormSchema();
expect(schema).toHaveLength(8);
});
});
describe("getTableColumns", () => {
it("应该返回一个数组", async () => {
const columns = await getTableColumns();
expect(Array.isArray(columns)).toBe(true);
});
it("应该包含任务编号列", async () => {
const columns = await getTableColumns();
const taskNoCol = columns.find(col => col.prop === "taskNo");
expect(taskNoCol).toEqual({
label: "任务编号",
prop: "taskNo",
width: "180px",
align: "left",
});
});
it("应该包含任务标题列", async () => {
const columns = await getTableColumns();
const titleCol = columns.find(col => col.prop === "title");
expect(titleCol).toEqual({
label: "任务标题",
prop: "title",
minWidth: "200px",
align: "left",
});
});
it("应该包含优先级列且使用 tag 显示", async () => {
const columns = await getTableColumns();
const priorityCol = columns.find(col => col.prop === "priority");
expect(priorityCol).toHaveProperty("useTag", true);
expect(priorityCol).toHaveProperty("tagOptions");
expect(priorityCol.label).toBe("优先级");
});
it("应该包含执行人列且有 formatter 函数", async () => {
const columns = await getTableColumns();
const assigneeCol = columns.find(col => col.prop === "assignees");
expect(assigneeCol.formatter).toBeInstanceOf(Function);
// 测试 formatter 函数
const row = {
assignees: [
{ assigneeName: "张三" },
{ assigneeName: "李四" },
],
};
const result = assigneeCol.formatter(row);
expect(result).toBe("张三,李四");
});
it("执行人列的 formatter 函数应该处理空列表", async () => {
const columns = await getTableColumns();
const assigneeCol = columns.find(col => col.prop === "assignees");
const row = { assignees: [] };
const result = assigneeCol.formatter(row);
expect(result).toBe("-");
});
it("执行人列的 formatter 函数应该处理 undefined", async () => {
const columns = await getTableColumns();
const assigneeCol = columns.find(col => col.prop === "assignees");
const row = {};
const result = assigneeCol.formatter(row);
expect(result).toBe("-");
});
it("应该包含完成状态列且有 formatter 函数", async () => {
const columns = await getTableColumns();
const statusCol = columns.find(col => col.prop === "status");
expect(statusCol.formatter).toBeInstanceOf(Function);
expect(statusCol).toHaveProperty("valueClass");
});
it("完成状态列的 formatter 函数应该正确处理状态值", async () => {
const columns = await getTableColumns();
const statusCol = columns.find(col => col.prop === "status");
expect(statusCol.formatter({ status: "UNFINISHED" })).toBe("未完成");
expect(statusCol.formatter({ status: "FINISHED" })).toBe("已完成");
expect(statusCol.formatter({ status: "" })).toBe("-");
});
it("完成状态列的 valueClass 函数应该返回正确的类名", async () => {
const columns = await getTableColumns();
const statusCol = columns.find(col => col.prop === "status");
expect(statusCol.valueClass({ status: "UNFINISHED" })).toBe("yellow-dot");
expect(statusCol.valueClass({ status: "FINISHED" })).toBe("green-dot");
});
it("应该包含截止时间列且有 valueClass 函数", async () => {
const columns = await getTableColumns();
const dueTimeCol = columns.find(col => col.prop === "dueTime");
expect(dueTimeCol.valueClass).toBeInstanceOf(Function);
});
it("应该包含 10 个列", async () => {
const columns = await getTableColumns();
expect(columns).toHaveLength(10);
});
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!