测试指南与常见问题解决
目录结构
tests/
├── unit/ # 单元测试
│ ├── profitMarginTable/ # 利润率测算表格组件测试
│ │ └── profitMarginTable.spec.js
│ ├── financialRules/ # 财务规则相关测试
│ └── merchantStep/ # 商户步骤相关测试
├── e2e/ # E2E 测试
│ └── profitMarginTable.spec.js
└── README.md # 本文档
运行测试
单元测试
# 运行所有单元测试
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 测试
# 安装 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
解决方案:
-
方案 A - 直接使用 npx 运行(推荐):
npx vue-cli-service test:unit tests/unit/xxx.spec.js -
方案 B - 使用更新后的 npm 脚本:
# 已移除 test:unit 的 openssl 参数 npm run test:unit -- tests/unit/xxx.spec.js -
方案 C - 使用 legacy 模式(如果构建需要):
# 某些旧依赖可能仍需要 openssl legacy 支持 npm run test:unit:legacy -- tests/unit/xxx.spec.js -
方案 D - 使用项目指定的 Node.js 版本:
# 项目配置 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包
解决方案:
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:
module.exports = {
// ...其他配置
transformIgnorePatterns: [
'node_modules/(?!(lodash-es|nanoid)/)'
],
};
问题 4: Failed to resolve directive: loading
错误信息:
[Vue warn]: Failed to resolve directive: loading
原因:
- 测试中使用了自定义指令
v-loading,但测试环境没有注册该指令
解决方案:
在测试配置中 stub 该指令:
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]
解决方案:
确保测试数据包含完整的字段结构:
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 配置:
const createWrapper = () => {
return shallowMount(Component, {
// ...其他配置
provide: {
formContext: null, // 或 mock 对象
},
});
};
问题 7: mounted 生命周期自动调用 API 导致测试失败
原因:
- 组件在
mounted钩子中自动调用getTableData() - 导致每个测试都会有额外的 API 调用
解决方案:
-
等待 mounted 完成后再清空 mock 记录:
wrapper = createWrapper(); await new Promise(resolve => setTimeout(resolve, 600)); getProductPackagesListApi.mockClear(); // 清空 mounted 时的调用 -
或者在测试中断言最后一次调用:
const calls = getProductPackagesListApi.mock.calls; const lastCall = calls[calls.length - 1][0]; expect(lastCall.currentPage).toBe(2);
测试最佳实践
1. Mock 外部依赖
jest.mock("@/views/goods/shelfProduct/api", () => ({
getProductPackagesListApi: jest.fn(),
}));
2. 使用 shallowMount 避免深度渲染
import { shallowMount } from "@vue/test-utils";
wrapper = shallowMount(Component, {
stubs: {
"el-table": true,
"el-button": true,
},
});
3. 清理测试状态
afterEach(() => {
if (wrapper) {
wrapper.destroy();
}
jest.clearAllMocks();
});
4. 测试边界情况
// 空数据
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