Commit 671461ed by Jaxon

feat(test): 添加完整的单元和E2E测试套件,修复Jest配置并更新测试脚本

新增Playwright E2E测试配置、测试用例与测试指南文档;新增d2-table、TableHeadSearch、利润率测算表格组件的单元测试文件;配置Jest的transformIgnorePatterns以支持lodash-es和nanoid等ES模块依赖;调整package.json的测试脚本,拆分出兼容旧版Node.js的test:unit:legacy命令,解决高版本Node.js的openssl参数报错问题;新增@playwright/test项目依赖。
1 parent 78a80afb
...@@ -10,6 +10,9 @@ module.exports = { ...@@ -10,6 +10,9 @@ module.exports = {
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest' '^.+\\.jsx?$': 'babel-jest'
}, },
transformIgnorePatterns: [
'node_modules/(?!(lodash-es|nanoid)/)'
],
moduleNameMapper: { moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1' '^@/(.*)$': '<rootDir>/src/$1'
}, },
......
This diff could not be displayed because it is too large.
...@@ -10,7 +10,8 @@ ...@@ -10,7 +10,8 @@
"build": "vue-cli-service build --no-module", "build": "vue-cli-service build --no-module",
"build:nomock": "vue-cli-service build --mode nomock", "build:nomock": "vue-cli-service build --mode nomock",
"lint": "vue-cli-service lint --fix", "lint": "vue-cli-service lint --fix",
"test:unit": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service test:unit", "test:unit": "vue-cli-service test:unit",
"test:unit:legacy": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service test:unit",
"report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report" "report": "set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build --report"
}, },
"dependencies": { "dependencies": {
...@@ -68,6 +69,7 @@ ...@@ -68,6 +69,7 @@
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12", "@babel/plugin-proposal-nullish-coalescing-operator": "^7.17.12",
"@babel/plugin-proposal-optional-chaining": "7.13.12", "@babel/plugin-proposal-optional-chaining": "7.13.12",
"@kazupon/vue-i18n-loader": "^0.4.1", "@kazupon/vue-i18n-loader": "^0.4.1",
"@playwright/test": "^1.60.0",
"@sentry/webpack-plugin": "^1.18.9", "@sentry/webpack-plugin": "^1.18.9",
"@vue/babel-helper-vue-jsx-merge-props": "^1.4.0", "@vue/babel-helper-vue-jsx-merge-props": "^1.4.0",
"@vue/cli-plugin-babel": "~5.0.8", "@vue/cli-plugin-babel": "~5.0.8",
......
/**
* Playwright E2E 测试配置
*
* 使用方法:
* 1. 安装 Playwright: npm install -D @playwright/test
* 2. 安装浏览器:npx playwright install
* 3. 运行测试:npx playwright test
* 4. 带 UI 运行:npx playwright test --ui
* 5. 运行特定测试:npx playwright test tests/e2e/profitMarginTable.spec.js
* 6. 生成报告:npx playwright show-report
*/
import { defineConfig, devices } from "@playwright/test";
export default defineConfig({
// 测试文件位置
testDir: "./tests/e2e",
// 超时时间
timeout: 30 * 1000,
// 每个测试的期望时间
expect: {
timeout: 5000,
},
// 失败重试次数
retries: 1,
// 并行执行配置
workers: 4,
// 是否失败即停止
failOnFlakyTests: false,
// 报告配置
reporter: [
["list"],
["html", { outputFolder: "playwright-report", open: "never" }],
],
// 共享配置
use: {
// 基础 URL
baseURL: process.env.BASE_URL || "http://localhost:8080",
// 截图配置
screenshot: "only-on-failure",
// 录屏配置
video: "retain-on-failure",
// 追踪配置
trace: "retain-on-failure",
// 浏览器上下文选项
actionTimeout: 10000,
navigationTimeout: 30000,
},
// 浏览器配置
projects: [
{
name: "chromium",
use: {
...devices["Desktop Chrome"],
viewport: { width: 1920, height: 1080 },
},
},
{
name: "firefox",
use: {
...devices["Desktop Firefox"],
viewport: { width: 1920, height: 1080 },
},
},
{
name: "webkit",
use: {
...devices["Desktop Safari"],
viewport: { width: 1920, height: 1080 },
},
},
// 移动端测试
{
name: "Mobile Chrome",
use: {
...devices["Pixel 5"],
},
},
{
name: "Mobile Safari",
use: {
...devices["iPhone 12"],
},
},
],
// Web 服务器配置 (可选,用于自动启动开发服务器)
// webServer: {
// command: "npm run dev",
// port: 8080,
// timeout: 120 * 1000,
// reuseExistingServer: true,
// },
});
# 测试指南与常见问题解决
## 目录结构
```
tests/
├── unit/ # 单元测试
│ ├── profitMarginTable/ # 利润率测算表格组件测试
│ │ └── profitMarginTable.spec.js
│ ├── financialRules/ # 财务规则相关测试
│ └── merchantStep/ # 商户步骤相关测试
├── e2e/ # E2E 测试
│ └── profitMarginTable.spec.js
└── README.md # 本文档
```
## 运行测试
### 单元测试
```bash
# 运行所有单元测试
npm run test:unit
# 运行特定测试文件
npm run test:unit -- tests/unit/profitMarginTable/profitMarginTable.spec.js
# 使用 legacy 模式(遇到 OpenSSL 问题时)
npm run test:unit:legacy -- tests/unit/profitMarginTable/profitMarginTable.spec.js
```
### E2E 测试
```bash
# 安装 Playwright (首次使用)
npm install -D @playwright/test
npx playwright install
# 运行所有 E2E 测试
npx playwright test
# 运行特定测试文件
npx playwright test tests/e2e/profitMarginTable.spec.js
# 带 UI 运行
npx playwright test --ui
# 生成报告
npx playwright show-report
```
---
## 常见问题与解决方案
### 问题 1: `--openssl-legacy-provider is not allowed in NODE_OPTIONS`
**错误信息:**
```
node: --openssl-legacy-provider is not allowed in NODE_OPTIONS
npm ERR! code ELIFECYCLE
npm ERR! errno 9
```
**原因:**
- Node.js 18+ 版本中,`--openssl-legacy-provider` 参数不允许通过 `NODE_OPTIONS` 环境变量设置
- 项目原本使用 Node.js 14(通过 volta 配置),但实际运行环境是 Node.js 18
**解决方案:**
1. **方案 A - 直接使用 npx 运行(推荐):**
```bash
npx vue-cli-service test:unit tests/unit/xxx.spec.js
```
2. **方案 B - 使用更新后的 npm 脚本:**
```bash
# 已移除 test:unit 的 openssl 参数
npm run test:unit -- tests/unit/xxx.spec.js
```
3. **方案 C - 使用 legacy 模式(如果构建需要):**
```bash
# 某些旧依赖可能仍需要 openssl legacy 支持
npm run test:unit:legacy -- tests/unit/xxx.spec.js
```
4. **方案 D - 使用项目指定的 Node.js 版本:**
```bash
# 项目配置 volta 使用 Node.js 14.21.3
# 如果已安装 volta,可以切换版本
volta install node@14.21.3
```
---
### 问题 2: `Cannot find module 'babel-jest'`
**错误信息:**
```
Error: Cannot find module 'babel-jest'
Require stack:
- node_modules/@vue/vue2-jest/lib/index.js
```
**原因:**
- 项目依赖中缺少 `babel-jest` 包
**解决方案:**
```bash
npm install --save-dev babel-jest@^27.5.1
```
---
### 问题 3: `SyntaxError: Unexpected token 'export'`
**错误信息:**
```
SyntaxError: Unexpected token 'export'
at Object.<anonymous> (node_modules/lodash-es/lodash.js:10)
```
**原因:**
- `lodash-es` 和 `nanoid` 等包使用 ES 模块语法
- Jest 默认不转换 `node_modules` 中的文件
**解决方案:**
在 `jest.config.js` 中添加 `transformIgnorePatterns`:
```javascript
module.exports = {
// ...其他配置
transformIgnorePatterns: [
'node_modules/(?!(lodash-es|nanoid)/)'
],
};
```
---
### 问题 4: `Failed to resolve directive: loading`
**错误信息:**
```
[Vue warn]: Failed to resolve directive: loading
```
**原因:**
- 测试中使用了自定义指令 `v-loading`,但测试环境没有注册该指令
**解决方案:**
在测试配置中 stub 该指令:
```javascript
const createWrapper = () => {
return mount(Component, {
// ...其他配置
directives: {
loading: {
bind() {},
update() {},
},
},
});
};
```
---
### 问题 5: `Cannot read properties of undefined (reading 'detailList')`
**错误信息:**
```
TypeError: Cannot read properties of undefined (reading 'detailList')
```
**原因:**
- 测试数据缺少必要的嵌套结构
- 组件中的 `getProductPackagesName` 函数访问 `row.detailList[0]`
**解决方案:**
确保测试数据包含完整的字段结构:
```javascript
const mockTableData = {
list: [
{
productType: 1,
productName: "测试商品 1",
detailList: [{ goodsAlias: "商品别名" }], // 必须包含此字段
revenue: 100,
// ...其他字段
},
],
};
```
---
### 问题 6: 组件测试中 mixin inject 问题
**错误信息:**
```
TypeError: Cannot read properties of undefined (reading 'xxx')
```
**原因:**
- 组件使用了 `inject: { formContext }`
- 测试环境中没有提供 `formContext`
**解决方案:**
在测试中提供 `provide` 配置:
```javascript
const createWrapper = () => {
return shallowMount(Component, {
// ...其他配置
provide: {
formContext: null, // 或 mock 对象
},
});
};
```
---
### 问题 7: mounted 生命周期自动调用 API 导致测试失败
**原因:**
- 组件在 `mounted` 钩子中自动调用 `getTableData()`
- 导致每个测试都会有额外的 API 调用
**解决方案:**
1. 等待 mounted 完成后再清空 mock 记录:
```javascript
wrapper = createWrapper();
await new Promise(resolve => setTimeout(resolve, 600));
getProductPackagesListApi.mockClear(); // 清空 mounted 时的调用
```
2. 或者在测试中断言最后一次调用:
```javascript
const calls = getProductPackagesListApi.mock.calls;
const lastCall = calls[calls.length - 1][0];
expect(lastCall.currentPage).toBe(2);
```
---
## 测试最佳实践
### 1. Mock 外部依赖
```javascript
jest.mock("@/views/goods/shelfProduct/api", () => ({
getProductPackagesListApi: jest.fn(),
}));
```
### 2. 使用 shallowMount 避免深度渲染
```javascript
import { shallowMount } from "@vue/test-utils";
wrapper = shallowMount(Component, {
stubs: {
"el-table": true,
"el-button": true,
},
});
```
### 3. 清理测试状态
```javascript
afterEach(() => {
if (wrapper) {
wrapper.destroy();
}
jest.clearAllMocks();
});
```
### 4. 测试边界情况
```javascript
// 空数据
test("处理空列表", async () => {
getProductPackagesListApi.mockResolvedValue({ list: [], total: 0 });
await wrapper.vm.getTableData();
expect(wrapper.vm.table.data).toEqual([]);
});
// 错误处理
test("API 失败时抛出错误", async () => {
getProductPackagesListApi.mockRejectedValue(new Error("API Error"));
try {
await wrapper.vm.getTableData();
} catch (e) {
expect(e.message).toBe("API Error");
}
});
```
---
## 文件清单
| 文件 | 描述 |
|------|------|
| `tests/unit/profitMarginTable/profitMarginTable.spec.js` | 利润率测算表格组件单元测试(29 个测试用例) |
| `tests/e2e/profitMarginTable.spec.js` | 利润率测算表格组件 E2E 测试 |
| `playwright.config.js` | Playwright E2E 测试配置 |
| `jest.config.js` | Jest 单元测试配置(已更新 transformIgnorePatterns) |
| `package.json` | 已更新 test:unit 脚本 |
---
## 版本信息
- Node.js: 18.20.8 (项目配置:14.21.3)
- npm: 10.8.2
- Vue: 2.6.10
- Jest: 27.1.0
- @vue/test-utils: 1.0.0-beta.29
- @playwright/test: 1.60.0
---
## 参考文档
- [Vue Test Utils 官方文档](https://vue-test-utils.vuejs.org/)
- [Jest 官方文档](https://jestjs.io/)
- [Playwright 官方文档](https://playwright.dev/)
/**
* @jest-environment jsdom
*/
import { createLocalVue } from "@vue/test-utils";
// 创建 Vue 实例
const localVue = createLocalVue();
describe("D2Table - 表格 + 分页组件 (逻辑测试)", () => {
let D2Table;
let vm;
// 模拟表格列配置
const mockTableColumns = [
{ label: "商品名", prop: "name", minWidth: 160 },
{ label: "价格", prop: "price", width: 100 },
];
beforeEach(() => {
jest.clearAllMocks();
delete require.cache[require.resolve("@/components/d2-table/index.vue")];
D2Table = require("@/components/d2-table/index.vue").default;
// 创建组件实例
const Component = { ...D2Table };
Component.data = function() {
return {
orderByType: "",
loading: false,
data: [],
page: { pageSize: 10, currentPage: 1 },
total: 10,
sortColum: "",
sort: "",
pagination: {},
mutiSelectArr: {},
};
};
vm = new (localVue.extend(Component))();
});
describe("组件定义", () => {
test("组件正确导出", () => {
expect(D2Table).toBeDefined();
expect(typeof D2Table).toBe("object");
expect(D2Table.name).toBe("D2Table");
});
test("组件注册了 TableHeadSearch 子组件", () => {
expect(D2Table.components.TableHeadSearch).toBeDefined();
});
});
describe("初始状态 - data", () => {
test("orderByType 初始为空字符串", () => {
expect(vm.orderByType).toBe("");
});
test("loading 初始为 false", () => {
expect(vm.loading).toBe(false);
});
test("data 初始为空数组", () => {
expect(vm.data).toEqual([]);
});
test("page 有默认分页参数", () => {
expect(vm.page).toEqual({
pageSize: 10,
currentPage: 1,
});
});
test("sortColum 和 sort 初始为空", () => {
expect(vm.sortColum).toBe("");
expect(vm.sort).toBe("");
});
test("mutiSelectArr 初始为空对象", () => {
expect(vm.mutiSelectArr).toEqual({});
});
});
describe("方法测试 - assignUniqueRowKeys", () => {
test("当 needUnique 为 false 时不处理数据", () => {
vm.tableParams = { needUnique: false, mutiSelectUniqueKey: "id" };
const testData = [{ name: "test" }];
vm.assignUniqueRowKeys(testData);
expect(testData[0].id).toBeUndefined();
});
test("当 needUnique 为 true 时写入唯一值", () => {
vm.tableParams = { needUnique: true, mutiSelectUniqueKey: "uniqueKey" };
const testData = [
{ name: "parent1", upgradeGoodsList: [{ name: "child1" }] },
{ name: "parent2" },
];
vm.assignUniqueRowKeys(testData);
expect(testData[0].uniqueKey).toBe(1);
expect(testData[0].upgradeGoodsList[0].uniqueKey).toBe(2);
expect(testData[1].uniqueKey).toBe(3);
});
test("空数组时不处理", () => {
vm.tableParams = { needUnique: true, mutiSelectUniqueKey: "id" };
expect(() => vm.assignUniqueRowKeys([])).not.toThrow();
});
test("非数组时不处理", () => {
vm.tableParams = { needUnique: true, mutiSelectUniqueKey: "id" };
expect(() => vm.assignUniqueRowKeys(null)).not.toThrow();
});
});
describe("方法测试 - getRowKey", () => {
test("优先使用 mutiSelectUniqueKey 作为 rowKey", () => {
vm.tableParams = { mutiSelectUniqueKey: "customKey" };
const row = { customKey: "abc123", id: 999 };
expect(vm.getRowKey(row)).toBe("abc123");
});
test("无 customKey 时使用 id 字段", () => {
vm.tableParams = {};
expect(vm.getRowKey({ id: 1 })).toBe("1");
});
test("无 id 时使用 baseGoodsId 字段", () => {
vm.tableParams = {};
expect(vm.getRowKey({ baseGoodsId: 2 })).toBe("2");
});
test("所有字段都缺失时使用 fallback 值", () => {
vm.tableParams = {};
vm._rowKeyFallback = 0;
expect(vm.getRowKey({})).toBe("row_1");
expect(vm.getRowKey({})).toBe("row_2");
});
});
describe("方法测试 - sortChange", () => {
const mockSortObj = {
name: { asc: 1, desc: 2 },
price: { asc: 3, desc: 4 },
};
test("排序变化时更新排序字段", () => {
vm.sortObj = mockSortObj;
vm.sortChange({
column: { prop: "name" },
prop: "name",
order: "descending",
});
expect(vm.sortColum).toBe("name");
expect(vm.sort).toBe("descending");
});
test("排序取消时清空排序字段", () => {
vm.sortObj = mockSortObj;
vm.sortChange({
column: { prop: "name" },
prop: "name",
order: null,
});
expect(vm.sortColum).toBe("");
expect(vm.sort).toBe(null); // order 为 null 时 sort 也被设置为 null
});
});
describe("方法测试 - handleSelect", () => {
test("handleSelect 更新 mutiSelectArr", () => {
const mockSelection = [{ id: 1 }, { id: 2 }];
vm.tableParams = { mutiSelectName: "test" };
vm.handleSelect(mockSelection);
expect(vm.mutiSelectArr.test).toEqual(mockSelection);
});
});
describe("方法测试 - clearMutiSelect", () => {
test("clearMutiSelect 清空选中项", () => {
const mockClearSelection = jest.fn();
vm.tableParams = { mutiSelectName: "test" };
vm.mutiSelectArr.test = [{ id: 1 }];
vm.$refs = { testMutiTable: { clearSelection: mockClearSelection } };
vm.clearMutiSelect();
expect(vm.mutiSelectArr.test).toEqual([]);
expect(mockClearSelection).toHaveBeenCalled();
});
});
describe("方法测试 - handleTableHeadChange", () => {
test("handleTableHeadChange 触发事件", () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
const mockObj = { searchItemName: "type", checkedList: [1, 2] };
vm.handleTableHeadChange(mockObj);
expect(mockEmit).toHaveBeenCalledWith("handleTableHeadChange", mockObj);
});
});
describe("方法测试 - handleSizeChange", () => {
test("handleSizeChange 更新 pageSize", async () => {
await vm.handleSizeChange(20);
expect(vm.page.pageSize).toBe(20);
});
test("handleSizeChange 有 getListApi 时调用 refreshTable", async () => {
const refreshTableMock = jest.fn();
vm.getListApi = jest.fn();
vm.refreshTable = refreshTableMock;
await vm.handleSizeChange(50);
expect(refreshTableMock).toHaveBeenCalledWith(false);
});
});
describe("方法测试 - handleCurrentChange", () => {
test("handleCurrentChange 更新 currentPage", async () => {
await vm.handleCurrentChange(3);
expect(vm.page.currentPage).toBe(3);
});
test("handleCurrentChange 有 getListApi 时调用 refreshTable", async () => {
const refreshTableMock = jest.fn();
vm.getListApi = jest.fn();
vm.refreshTable = refreshTableMock;
await vm.handleCurrentChange(2);
expect(refreshTableMock).toHaveBeenCalledWith(false);
});
});
describe("方法测试 - handleHeaderBatch", () => {
test("handleHeaderBatch 调用列配置的函数", () => {
const mockFn = jest.fn();
const currentItem = { headerImgObj: { fn: mockFn } };
vm.handleHeaderBatch(currentItem);
expect(mockFn).toHaveBeenCalledWith(currentItem);
});
test("handleHeaderBatch 无函数时不报错", () => {
const currentItem = { headerImgObj: {} };
expect(() => vm.handleHeaderBatch(currentItem)).not.toThrow();
});
});
describe("方法测试 - scroll", () => {
test("scroll 触发 scroll 事件", () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
const mockEvent = { target: { scrollTop: 100 } };
vm.scroll(mockEvent);
expect(mockEmit).toHaveBeenCalledWith("scroll", mockEvent);
});
});
describe("方法测试 - handleSelectRow", () => {
test("handleSelectRow 触发 selectRow 事件", () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
const mockSelection = [{ id: 1 }];
const mockRow = { id: 1, name: "商品 1" };
vm.handleSelectRow(mockSelection, mockRow);
expect(mockEmit).toHaveBeenCalledWith("selectRow", mockSelection, mockRow);
});
});
describe("方法测试 - handleSelectAll", () => {
test("handleSelectAll 触发 selectAll 事件", () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
const mockSelection = [{ id: 1 }, { id: 2 }];
vm.handleSelectAll(mockSelection);
expect(mockEmit).toHaveBeenCalledWith("selectAll", mockSelection);
});
});
describe("方法测试 - refreshEmit", () => {
test("refreshEmit 触发事件并刷新表格", async () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
const refreshTableMock = jest.fn();
vm.refreshTable = refreshTableMock;
await vm.refreshEmit();
expect(mockEmit).toHaveBeenCalledWith("searchChange");
expect(refreshTableMock).toHaveBeenCalledWith(true, true);
});
});
describe("方法测试 - handleCurrentChange 分页事件", () => {
test("handleSizeChange 触发 pageChange 事件", async () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
await vm.handleSizeChange(20);
expect(mockEmit).toHaveBeenCalledWith("pageChange", vm.page);
});
test("handleCurrentChange 触发 pageChange 事件", async () => {
const mockEmit = jest.fn();
vm.$emit = mockEmit;
await vm.handleCurrentChange(3);
expect(mockEmit).toHaveBeenCalledWith("pageChange", vm.page);
});
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!