Commit a58a729d by Jaxon

chron: 测试文件夹 更改目录结构

1 parent 640b72b7
Showing 42 changed files with 0 additions and 3609 deletions
# 测试指南与常见问题解决
## 目录结构
```
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/)
# 真实脱敏 Fixture
将脱敏后的详情/提交 JSON 放在此目录,文件名建议:
- `detail-with-special.json` — 全部品类 + 多特殊品类详情响应
- `submit-after-delete-special.json` — 删光特殊品类后的 submit body
单测通过 `loadFixture(name)` 优先加载 `real/`,不存在则回退 `synthetic/`。
{
"goodsTypeGroupRules": [
{
"groupType": 1,
"groupDivisionRuleId": 17805,
"groupSettleRuleId": 17942,
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
}
]
}
{
"goodsTypeGroupRules": [
{
"groupType": 1,
"groupDivisionRuleId": 17805,
"groupSettleRuleId": 17942,
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
},
{
"groupType": 2,
"groupDivisionRuleId": 17806,
"groupSettleRuleId": 17943,
"goodsSource": 1,
"goodsTypeGroupRelations": [{ "goodsType": "G1" }],
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
},
{
"groupType": 2,
"groupDivisionRuleId": 17808,
"groupSettleRuleId": 17944,
"goodsSource": 1,
"goodsTypeGroupRelations": [{ "goodsType": "G2" }],
"shop4sDeductChargeFlag": "Y",
"partnerDeductChargeFlag": "Y",
"goodsCostFlag": "N",
"expenseCategoryRules": [
{
"calculateMode": 1,
"expenseCategoryCalculateType": 1,
"expenseCategoryValue": "10"
}
],
"merchantDistributionRules": [{ "merchantId": "100" }],
"owningMerchantDistributionRules": [{ "merchantId": "100" }]
}
]
}
{
"description": "删光特殊品类 Tab 后期望的增量提交形态(合成)",
"incrementalRules": [
{
"groupType": 1,
"groupDivisionRuleId": "17805",
"groupSettleRuleId": 17942,
"type": "UPDATE",
"tabPaneIndex": 0
}
],
"pendingDeletes": [
{ "groupType": 2, "groupDivisionRuleId": "17806" },
{ "groupType": 2, "groupDivisionRuleId": "17808" }
],
"mergedSubmitExpectation": {
"firstEntryType": "UPDATE",
"firstEntryId": "17805",
"deleteIds": ["17806", "17808"]
}
}
import {
IMPORT_BILL_FILE_RULE,
IMPORT_BILL_TYPE_OPTIONS,
buildImportBillFormData,
buildImportBillPayload,
buildImportTemplateDownloadTask,
getImportPollStatus
} from "@/views/financeManage/accountStateManage/importBill"
describe("importBill helpers", () => {
it("limits import file to one Excel file no larger than 10M", () => {
expect(IMPORT_BILL_FILE_RULE.extensions).toEqual([".xls", ".xlsx"])
expect(IMPORT_BILL_FILE_RULE.accept).toBe(".xls,.xlsx")
expect(IMPORT_BILL_FILE_RULE.maxSizeMb).toBe(10)
expect(IMPORT_BILL_FILE_RULE.maxCount).toBe(1)
})
it("keeps bill type options fixed", () => {
expect(IMPORT_BILL_TYPE_OPTIONS).toEqual([
{ value: "1", label: "流量方对账单" },
{ value: "2", label: "服务商对账单" }
])
})
it("builds glsx-combi-form data with bill type before file", () => {
const names = buildImportBillFormData().map(item => item.name)
expect(names).toEqual(["billType", "fileName"])
})
it("builds import payload as extension at base64", () => {
const payload = buildImportBillPayload({
billType: "1",
fileName: "demo.xlsx",
base64: "AAA111"
})
expect(payload).toEqual({
billType: "1",
file: "xlsx@AAA111"
})
})
it("normalizes poll status", () => {
expect(getImportPollStatus({ progress: 50, failNum: 0 })).toBe("processing")
expect(getImportPollStatus({ progress: 100, failNum: 0 })).toBe("success")
expect(getImportPollStatus({ progress: 100, failNum: 2 })).toBe("failed")
})
it("builds import template download task by bill type", () => {
const task = buildImportTemplateDownloadTask("1")
const exportParam = JSON.parse(task.exportParam)
expect(task.name).toBe("对账单导入模板")
expect(exportParam.billType).toBe("SHOP")
expect(exportParam.method).toBe("dj.api.smartcarlife.reconciliationBill.merchant.template.export.async")
})
})
import {
MARKET_TRANSFER_UPLOAD_RULE,
EXPENSE_CATEGORY_OPTIONS,
FORM_COMPONENT_RULE,
buildMarketTransferFormData,
buildMarketTransferDownloadParams,
buildMarketTransferSubmitParams,
getVisibleAmountFields,
normalizeApprovedMarketTransferFees,
mapMarketFeeResults
} from "@/views/financeManage/accountStateManage/marketTransfer"
describe("marketTransfer helpers", () => {
it("shows amount fields only for selected expense categories", () => {
const fields = getVisibleAmountFields([706, 900])
expect(fields.map(item => item.id)).toEqual([706, 900])
})
it("hides amount fields for expense categories already in approval", () => {
const fields = getVisibleAmountFields([706, 808, 900], [706, 900])
expect(fields.map(item => item.id)).toEqual([808])
})
it("maps market fee result rows by expense category id", () => {
const result = mapMarketFeeResults({
list: [
{ expenseCategoryId: 706, expenseCategoryResult: 11 },
{ expenseCategoryId: 900, expenseCategoryResult: 22 }
],
expenseCategoryTotalResult: 1.17
})
expect(result.amountMap).toEqual({ 706: 11, 900: 22 })
expect(result.totalAmount).toBe(1.17)
})
it("normalizes approved market transfer fees for default checked readonly categories", () => {
const result = normalizeApprovedMarketTransferFees([
{ expenseCategoryId: 706, expenseCategoryResult: 11 },
{ expenseCategoryId: 706, expenseCategoryResult: 12 },
{ expenseCategoryId: 900, expenseCategoryResult: 22 },
{ expenseCategoryId: null, expenseCategoryResult: 33 }
])
expect(result.expenseCategoryIds).toEqual([706, 900])
expect(result.amountMap).toEqual({ 706: 12, 900: 22 })
expect(result.totalAmount).toBe(34)
})
it("keeps the expense category ids fixed", () => {
expect(EXPENSE_CATEGORY_OPTIONS.map(item => item.id)).toEqual([706, 808, 809, 901, 900])
})
it("uses the requested voucher upload rule", () => {
expect(MARKET_TRANSFER_UPLOAD_RULE.extensions).toEqual([
".xls",
".xlsx",
".doc",
".docx",
".pdf",
".jpg",
".jpeg",
".png",
".bmp"
])
expect(MARKET_TRANSFER_UPLOAD_RULE.maxSizeMb).toBe(10)
expect(MARKET_TRANSFER_UPLOAD_RULE.maxCount).toBe(4)
expect(MARKET_TRANSFER_UPLOAD_RULE.accept).toBe(".xls,.xlsx,.doc,.docx,.pdf,.jpg,.jpeg,.png,.bmp")
})
it("documents that finance forms should use glsx-combi-form", () => {
expect(FORM_COMPONENT_RULE.component).toBe("glsx-combi-form")
expect(FORM_COMPONENT_RULE.requiredFor).toContain("finance dialog forms")
})
it("keeps invoice remark before voucher in the market transfer form", () => {
const names = buildMarketTransferFormData().map(item => item.name)
expect(names.indexOf("invoiceRemark")).toBeLessThan(names.indexOf("fileUrlList"))
})
it("adds a horizontal-scroll popper class for bank account options", () => {
const bankAccount = buildMarketTransferFormData().find(item => item.name === "rcvMerchantId")
expect(bankAccount.attrs.popperClass).toBe("market-transfer-account-popper")
})
it("submits voucher urls as a fileUrlList array", () => {
const params = buildMarketTransferSubmitParams({
id: "bill-1",
remark: "ok",
expenseCategoryIds: [706, 808, 900],
fileUrlList: [
{ fileUrl: "https://example.com/a.png" },
{ fileUrl: "" },
{ fileUrl: "https://example.com/b.jpg" }
]
}, [706, 900])
expect(params.expenseCategoryIds).toEqual([808])
expect(params.fileUrlList).toEqual(["https://example.com/a.png", "https://example.com/b.jpg"])
expect(params.fileUrl).toBeUndefined()
expect(params.id).toBe("bill-1")
expect(params.remark).toBe("ok")
})
it("downloads details only for unchecked approval expense categories", () => {
const params = buildMarketTransferDownloadParams({
reconciliationBillId: "bill-1",
expenseCategoryIds: [706, 808, 900]
}, [706, 900])
expect(params).toEqual({
reconciliationBillId: "bill-1",
expenseCategoryIds: [808]
})
})
})
/**
* @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);
});
});
});
import {
appendDeleteOpsToIncremental
} from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
describe("appendDeleteOpsToIncremental", () => {
test("空 deletedEntries → 原样返回", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
expect(appendDeleteOpsToIncremental(base, null)).toEqual(base)
expect(appendDeleteOpsToIncremental(base, [])).toEqual(base)
})
test("追加 DELETE(字符串 id)", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
const out = appendDeleteOpsToIncremental(base, ["17806"])
expect(out).toHaveLength(2)
expect(out[1]).toEqual({
type: GOODS_TYPE_GROUP_RULE_OP.DELETE,
groupDivisionRuleId: "17806"
})
})
test("追加 DELETE(完整规则对象)", () => {
const base = [{ type: GOODS_TYPE_GROUP_RULE_OP.UPDATE, groupDivisionRuleId: "17805" }]
const out = appendDeleteOpsToIncremental(base, [
{ groupType: 2, groupDivisionRuleId: 17808, groupSettleRuleId: 17944 }
])
expect(out[1].type).toBe(GOODS_TYPE_GROUP_RULE_OP.DELETE)
expect(out[1].groupDivisionRuleId).toBe("17808")
expect(out[1].groupType).toBe(2)
expect(out[1].groupSettleRuleId).toBe(17944)
expect(out[1].tabPaneIndex).toBeUndefined()
})
test("deletedEntries 内重复 id → 去重", () => {
const out = appendDeleteOpsToIncremental([], ["17806", "17806", 17806])
expect(out).toHaveLength(1)
expect(out[0].groupDivisionRuleId).toBe("17806")
})
test("与 incremental 已有 DELETE 重复 → 跳过", () => {
const base = [
{ type: GOODS_TYPE_GROUP_RULE_OP.DELETE, groupDivisionRuleId: "17806" }
]
const out = appendDeleteOpsToIncremental(base, ["17806", "17808"])
expect(out).toHaveLength(2)
expect(out[1].groupDivisionRuleId).toBe("17808")
})
test("无 id 的对象 entry → 不产出 DELETE", () => {
const out = appendDeleteOpsToIncremental([], [{ groupType: 2, sessionAdded: true }])
expect(out).toHaveLength(0)
})
test("id 字段 fallback", () => {
const out = appendDeleteOpsToIncremental([], [{ id: "99", groupType: 2 }])
expect(out[0].groupDivisionRuleId).toBe("99")
})
})
import {
buildDivisionRuleTestParams,
buildDivisionRuleTestRetestParams,
buildDivisionRuleTestMoneyValidParams,
buildDivisionRuleTestUpdateMainProgressParams
} from "@/views/systemConfig/merchant/financialRules/utils/buildDivisionRuleTestParams"
describe("buildDivisionRuleTestParams", () => {
it("includes divisionRuleId from financial detail, not goodsTypeGroupDivisionId", () => {
const params = buildDivisionRuleTestParams({
merchantId: "m1",
sceneType: 1,
paymentChannelId: "ch1",
divisionRuleId: 4928,
baseSceneCode: "SC001"
})
expect(params).toEqual({
merchantId: "m1",
sceneType: 1,
paymentChannelId: "ch1",
divisionRuleId: 4928,
baseSceneCode: "SC001"
})
expect(params.goodsTypeGroupDivisionId).toBeUndefined()
})
it("omits empty divisionRuleId", () => {
const params = buildDivisionRuleTestParams({
merchantId: "m1",
sceneType: 1,
divisionRuleId: ""
})
expect(params.divisionRuleId).toBeUndefined()
})
it("buildDivisionRuleTestRetestParams only divisionRuleId and paymentChannelId", () => {
const params = buildDivisionRuleTestRetestParams({
divisionRuleId: 4928,
paymentChannelId: "ch1",
merchantId: "m1",
sceneType: 1
})
expect(params).toEqual({
divisionRuleId: 4928,
paymentChannelId: "ch1"
})
})
it("buildDivisionRuleTestMoneyValidParams requires explicit divisionRuleId", () => {
const testMerchantDivisions = [
{ merchantId: "m1", distributionMoney: "1.0", confirmDivisionMoney: "1.0" }
]
const params = buildDivisionRuleTestMoneyValidParams({
testObj: { paymentChannelId: "ch1", divisionRuleId: 100 },
testMerchantDivisions
})
expect(params.divisionRuleId).toBeUndefined()
expect(params.paymentChannelId).toBe("ch1")
expect(params.testMerchantDivisions).toEqual(testMerchantDivisions)
})
it("buildDivisionRuleTestMoneyValidParams uses explicit divisionRuleId and paymentChannelId", () => {
const testMerchantDivisions = [
{ merchantId: "m1", distributionMoney: "1.0", confirmDivisionMoney: "1.0" }
]
const params = buildDivisionRuleTestMoneyValidParams({
testObj: { paymentChannelId: "ch2" },
testMerchantDivisions,
divisionRuleId: 4928
})
expect(params).toEqual({
divisionRuleId: 4928,
paymentChannelId: "ch2",
testMerchantDivisions
})
expect(params.goodsTypeGroupDivisionId).toBeUndefined()
})
it("buildDivisionRuleTestUpdateMainProgressParams three fields", () => {
const params = buildDivisionRuleTestUpdateMainProgressParams({
divisionRuleId: 4928,
paymentChannelId: "ch1",
progress: 2
})
expect(params).toEqual({
divisionRuleId: 4928,
paymentChannelId: "ch1",
progress: 2
})
})
it("buildDivisionRuleTestUpdateMainProgressParams omits invalid progress", () => {
const params = buildDivisionRuleTestUpdateMainProgressParams({
divisionRuleId: 1,
paymentChannelId: "ch1",
progress: 0
})
expect(params.progress).toBeUndefined()
})
})
/**
* @jest-environment jsdom
*/
import { buildFullMergedGoodsTypeGroupRules } from "@/views/systemConfig/merchant/financialRules/utils/buildFullMergedGoodsTypeGroupRules"
import { loadFixture } from "./helpers/financialRulesTestHelpers"
describe("buildFullMergedGoodsTypeGroupRules", () => {
test("validated 槽位用快照,其余用缓存 fillDj", () => {
const fixture = loadFixture("all-plus-special-tabs")
const caches = fixture.goodsTypeGroupRules
const validated = { 1: { groupType: 2, groupDivisionRuleId: "validated-only" } }
const out = buildFullMergedGoodsTypeGroupRules({
tabCount: 3,
validatedByIndex: validated,
slotCaches: caches
})
expect(out).toHaveLength(3)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[1].groupDivisionRuleId).toBe("validated-only")
expect(out[2].groupDivisionRuleId).toBe(17808)
})
test("空缓存槽位 → fillDj 空对象", () => {
const out = buildFullMergedGoodsTypeGroupRules({
tabCount: 1,
validatedByIndex: {},
slotCaches: []
})
expect(out).toHaveLength(1)
expect(out[0]).toEqual({})
})
})
import { buildGoodsTypeGroupIncrementalRules } from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
describe("buildGoodsTypeGroupIncrementalRules", () => {
test("onlyActiveTab: single index with id yields UPDATE", () => {
const validatedByIndex = {
0: { groupDivisionRuleId: "99", foo: 1 }
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[0],
true
)
expect(out).toHaveLength(1)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].tabPaneIndex).toBe(0)
})
test("onlyActiveTab: no id yields ADD", () => {
const validatedByIndex = {
1: { foo: 1 }
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[1],
true
)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.ADD)
})
test("full submit: multiple indices", () => {
const validatedByIndex = {
0: { groupDivisionRuleId: "a" },
2: {}
}
const out = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
[0, 2],
false
)
expect(out).toHaveLength(2)
expect(out[0].tabPaneIndex).toBe(0)
expect(out[1].tabPaneIndex).toBe(2)
})
})
import {
buildStep2DisplayMerchants,
buildStep3VerifyMerchants,
isMerchantTestCompleted,
randomAllocatePool,
sumDisplayDivisionMoney,
isTotalProfitAmountValid,
PLATFORM_FIXED_AMOUNT,
ALLOCATABLE_POOL
} from "@/views/systemConfig/merchant/financialRules/utils/buildStep2DisplayMerchants"
describe("buildStep2DisplayMerchants", () => {
it("randomAllocatePool sums to 3", () => {
const amounts = randomAllocatePool(
[{}, {}, {}],
() => 0.5
)
const sum = amounts.reduce((a, b) => a + b, 0)
expect(Math.round(sum * 100)).toBe(Math.round(ALLOCATABLE_POOL * 100))
})
it("shows distributionMoney in step2 input", () => {
const list = [
{ merchantName: "流量", targetType: 1, distributionMoney: "2.5" },
{ merchantName: "平台", targetType: 4, distributionMoney: "0.5" }
]
const display = buildStep2DisplayMerchants(list)
expect(display.find((m) => m.merchantName === "流量").displayDivisionMoney).toBe("2.5")
expect(display.find((m) => m.merchantName === "平台").displayDivisionMoney).toBe("0.5")
})
it("distributionMoney 0 or empty means testCompleted", () => {
expect(isMerchantTestCompleted({ distributionMoney: 0 })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "0" })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "" })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: null })).toBe(true)
expect(isMerchantTestCompleted({ distributionMoney: "1.5" })).toBe(false)
const display = buildStep2DisplayMerchants([
{ merchantName: "已测", targetType: 2, distributionMoney: 0 },
{ merchantName: "待测", targetType: 1, distributionMoney: "3" }
])
expect(display.find((m) => m.merchantName === "已测").testCompleted).toBe(true)
expect(display.find((m) => m.merchantName === "已测").displayDivisionMoney).toBe("")
expect(display.find((m) => m.merchantName === "待测").testCompleted).toBe(false)
expect(display.find((m) => m.merchantName === "待测").displayDivisionMoney).toBe("3")
})
it("platform fallback when no distributionMoney", () => {
const list = [
{ merchantName: "流量", targetType: 1, distributionMoney: "3" },
{ merchantName: "平台", targetType: 4, distributionMoney: "0.5" }
]
const display = buildStep2DisplayMerchants(list, { randomFn: () => 1 })
expect(display.find((m) => m.merchantName === "平台").displayDivisionMoney).toBe("0.5")
})
it("isTotalProfitAmountValid excludes completed merchants", () => {
const merchants = [
{ testCompleted: true, displayDivisionMoney: "" },
{ testCompleted: false, displayDivisionMoney: "0.5" },
{ testCompleted: false, displayDivisionMoney: "3" }
]
expect(isTotalProfitAmountValid(merchants)).toBe(true)
expect(sumDisplayDivisionMoney(merchants)).toBe(3.5)
})
it("uses cache when distributionMoney missing on refetch", () => {
const list = [
{ merchantId: "1", merchantName: "A", targetType: 1, distributionMoney: "3" }
]
const first = buildStep2DisplayMerchants(list)
const cache = { 1: first[0].displayDivisionMoney }
const second = buildStep2DisplayMerchants(
[{ merchantId: "1", merchantName: "A", targetType: 1, distributionMoney: "3" }],
{ randomFn: () => 0.9, cachedAllocations: cache }
)
expect(second[0].displayDivisionMoney).toBe("3")
})
it("buildStep3VerifyMerchants shares testCompleted", () => {
const list = [
{ merchantName: "A", distributionMoney: 0 },
{ merchantName: "B", distributionMoney: "1.2", confirmDivisionMoney: "1.2" }
]
const step3 = buildStep3VerifyMerchants(list)
expect(step3[0].testCompleted).toBe(true)
expect(step3[1].testCompleted).toBe(false)
expect(step3[1].confirmDivisionMoney).toBe("1.2")
})
})
import { buildWebSocketUrl } from "@/views/systemConfig/merchant/financialRules/utils/buildWebSocketUrl"
describe("buildWebSocketUrl", () => {
it("uses wss on https pages for host-only url", () => {
expect(buildWebSocketUrl("host/path?query", "https:")).toBe(
"wss://host/path?query"
)
})
it("uses ws on http pages for host-only url", () => {
expect(buildWebSocketUrl("host/path", "http:")).toBe("ws://host/path")
})
it("upgrades ws:// to wss:// on https pages", () => {
expect(buildWebSocketUrl("ws://host/path", "https:")).toBe("wss://host/path")
})
it("keeps wss:// on https pages", () => {
expect(buildWebSocketUrl("wss://host/path", "https:")).toBe("wss://host/path")
})
it("returns empty string for invalid input", () => {
expect(buildWebSocketUrl("", "https:")).toBe("")
expect(buildWebSocketUrl(null, "https:")).toBe("")
})
it("strips leading // before adding scheme", () => {
expect(buildWebSocketUrl("//host/path", "http:")).toBe("ws://host/path")
})
})
import {
splitExpenseRulesByTarget,
hasWholeOrderCalculateMode,
computeCalculateModeConflicts
} from "@/views/systemConfig/merchant/financialRules/utils/calculateModeConflict"
describe("calculateModeConflict", () => {
test("splitExpenseRulesByTarget groups by targetType", () => {
const rules = [
{ targetType: 1, id: "a" },
{ targetType: 2, id: "b" },
{ targetType: 3, id: "c" }
]
const { trafficSide, serviceProvider, platformPublic } =
splitExpenseRulesByTarget(rules)
expect(trafficSide).toHaveLength(1)
expect(serviceProvider).toHaveLength(1)
expect(platformPublic).toHaveLength(1)
})
test("hasWholeOrderCalculateMode", () => {
expect(hasWholeOrderCalculateMode([{ calculateMode: 1 }])).toBe(false)
expect(hasWholeOrderCalculateMode([{ calculateMode: 2 }])).toBe(true)
})
test("computeCalculateModeConflicts detects platform whole-order vs traffic category mode", () => {
const goodsTypeGroupRules = [
{
expenseCategoryRules: [
{ targetType: 3, calculateMode: 2 },
{
targetType: 1,
calculateMode: 1,
expenseCategoryCalculateType: 8,
children: []
}
]
}
]
const { errorTips, tabErrors } = computeCalculateModeConflicts(
goodsTypeGroupRules
)
expect(errorTips).toBeGreaterThan(0)
expect(tabErrors[0]).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import { collectGoodsTypeGroupRulesFromTabs } from "@/views/systemConfig/merchant/financialRules/utils/collectGoodsTypeGroupRulesFromTabs"
describe("collectGoodsTypeGroupRulesFromTabs", () => {
test("激活 Tab 走 mergeChildClassificationPayload", () => {
const caches = [
{ groupType: 1, groupDivisionRuleId: 17805, expenseCategoryRules: [{ id: 1 }] }
]
const tabs = [{ name: "1", title: "全部品类" }]
const out = collectGoodsTypeGroupRulesFromTabs({
editableTabs: tabs,
slotCaches: caches,
getChildPayloadByPaneName: () => ({ groupType: 1, expenseCategoryRules: [{ id: 1 }] })
})
expect(out[0].groupDivisionRuleId).toBe(17805)
})
test("非激活 Tab 读缓存", () => {
const caches = [
{ groupType: 1, groupDivisionRuleId: 17805 },
{ groupType: 2, groupDivisionRuleId: 17806 }
]
const tabs = [{ name: "1" }, { name: "2" }]
const out = collectGoodsTypeGroupRulesFromTabs({
editableTabs: tabs,
slotCaches: caches,
getChildPayloadByPaneName: (name) => (name === "1" ? { groupType: 1 } : null)
})
expect(out[1].groupDivisionRuleId).toBe(17806)
expect(out[1].groupType).toBe(2)
})
})
import {
isDivisionRuleAutoTestPending,
hasPendingDivisionRuleAutoTest,
findPendingDivisionRuleAutoTestIndices,
findDivisionRuleTestByChannelId,
buildDivisionRuleAutosByChannelId,
shouldShowDivisionTestButton
} from "@/views/systemConfig/merchant/financialRules/utils/divisionRuleAutoTest"
describe("divisionRuleAutoTest", () => {
it("isDivisionRuleAutoTestPending: strict testFlag N and autoFlag Y", () => {
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y", testFlag: "N" })
).toBe(true)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y", testFlag: "Y" })
).toBe(false)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "Y" })
).toBe(false)
expect(
isDivisionRuleAutoTestPending({ autoFlag: "N", testFlag: "N" })
).toBe(false)
})
it("hasPendingDivisionRuleAutoTest", () => {
const list = [
{ autoFlag: "Y", testFlag: "Y" },
{ autoFlag: "Y", testFlag: "N" }
]
expect(hasPendingDivisionRuleAutoTest(list)).toBe(true)
expect(hasPendingDivisionRuleAutoTest([{ autoFlag: "Y", testFlag: "Y" }])).toBe(false)
})
it("findPendingDivisionRuleAutoTestIndices", () => {
const list = [
{ autoFlag: "N", testFlag: "N" },
{ autoFlag: "Y", testFlag: "N" },
{ autoFlag: "Y", testFlag: "Y" }
]
expect(findPendingDivisionRuleAutoTestIndices(list)).toEqual([1])
})
it("findDivisionRuleTestByChannelId matches paymentChannelId", () => {
const tests = [
{ paymentChannelId: "ch1", divisionRuleTestItem: { orderCode: "A" } },
{
paymentChannelId: "ch2",
divisionRuleTestItem: { paymentChannelId: "ch2", orderCode: "B" }
}
]
expect(findDivisionRuleTestByChannelId(tests, "ch2").divisionRuleTestItem.orderCode).toBe("B")
expect(findDivisionRuleTestByChannelId(tests, "ch9")).toBe(null)
})
it("buildDivisionRuleAutosByChannelId", () => {
const map = buildDivisionRuleAutosByChannelId([
{ paymentChannelId: 1, autoFlag: "Y", testFlag: "N" },
{ paymentChannelId: 2, autoFlag: "N", testFlag: "N" }
])
expect(map[1]).toEqual({ paymentChannelId: 1, autoFlag: "Y", testFlag: "N" })
expect(map[2].autoFlag).toBe("N")
})
it("buildDivisionRuleAutosByChannelId: snapshot isolated from local autoFlag toggle", () => {
const channel = { paymentChannelId: 10, autoFlag: "N", testFlag: "N" }
const map = buildDivisionRuleAutosByChannelId([channel])
channel.autoFlag = "Y"
expect(map[10].autoFlag).toBe("N")
expect(
shouldShowDivisionTestButton(channel, map, "rule-1")
).toBe(false)
})
it("shouldShowDivisionTestButton: server pending and local auto on", () => {
const serverMap = buildDivisionRuleAutosByChannelId([
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" }
])
expect(
shouldShowDivisionTestButton(
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" },
serverMap,
"rule-1"
)
).toBe(true)
})
it("shouldShowDivisionTestButton: local auto on without server pending stays hidden", () => {
const serverMap = buildDivisionRuleAutosByChannelId([
{ paymentChannelId: 10, autoFlag: "N", testFlag: "N" }
])
expect(
shouldShowDivisionTestButton(
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" },
serverMap,
"rule-1"
)
).toBe(false)
})
it("shouldShowDivisionTestButton: no divisionRuleId", () => {
const serverMap = buildDivisionRuleAutosByChannelId([
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" }
])
expect(
shouldShowDivisionTestButton(
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" },
serverMap,
undefined
)
).toBe(false)
})
it("shouldShowDivisionTestButton: local auto off hides even if server pending", () => {
const serverMap = buildDivisionRuleAutosByChannelId([
{ paymentChannelId: 10, autoFlag: "Y", testFlag: "N" }
])
expect(
shouldShowDivisionTestButton(
{ paymentChannelId: 10, autoFlag: "N", testFlag: "N" },
serverMap,
"rule-1"
)
).toBe(false)
})
})
import {
mapSubProgressToUi,
isDivisionTestInProgress,
isDivisionTestPassed,
canNavigateToStep,
isStepReadOnly,
buildStepCompletedFlags,
resolveMaxReachedStepFromSubProgress,
resolveInitialWizardSteps,
shouldShowStep1OrderLinked,
isDivisionTestFailed,
shouldSyncWizardStepsFromProgress
} from "@/views/systemConfig/merchant/financialRules/utils/divisionTestStepProgress"
describe("divisionTestStepProgress", () => {
it("isDivisionTestInProgress", () => {
expect(isDivisionTestInProgress(34)).toBe(true)
expect(isDivisionTestInProgress(35)).toBe(true)
expect(isDivisionTestInProgress(36)).toBe(true)
expect(isDivisionTestInProgress(31)).toBe(true)
expect(isDivisionTestInProgress(30)).toBe(false)
})
it("isDivisionTestPassed", () => {
expect(isDivisionTestPassed(37)).toBe(true)
expect(isDivisionTestPassed(34)).toBe(false)
})
it("mapSubProgressToUi: 34 unpaid", () => {
const ui = mapSubProgressToUi(34, { orderCode: "" })
expect(ui.step1Paid).toBe(false)
expect(ui.currentStep).toBeUndefined()
})
it("mapSubProgressToUi: 35 paid but no display step mapping", () => {
const ui = mapSubProgressToUi(35, { orderCode: "ORD001" })
expect(ui.step1Paid).toBe(true)
expect(ui.currentStep).toBeUndefined()
})
it("mapSubProgressToUi: 31 with outTradeNo treated as paid", () => {
const ui = mapSubProgressToUi(31, { outTradeNo: "OUT001" })
expect(ui.step1Paid).toBe(true)
expect(ui.isFailed).toBe(true)
})
it("mapSubProgressToUi: 31 without outTradeNo unpaid failed", () => {
const ui = mapSubProgressToUi(31, {})
expect(ui.step1Paid).toBe(false)
expect(ui.isFailed).toBe(true)
})
it("shouldShowStep1OrderLinked: 31 with outTradeNo", () => {
expect(
shouldShowStep1OrderLinked({
subProgress: 31,
outTradeNo: "OUT001"
})
).toBe(true)
})
it("shouldShowStep1OrderLinked: maxReachedStep>1 back to step1", () => {
expect(
shouldShowStep1OrderLinked({
step1Paid: false,
maxReachedStep: 3,
viewStep: 1
})
).toBe(true)
})
it("shouldShowStep1OrderLinked: 34 unpaid on step1", () => {
expect(
shouldShowStep1OrderLinked({
step1Paid: false,
subProgress: 34,
maxReachedStep: 1,
viewStep: 1
})
).toBe(false)
})
it("isDivisionTestFailed", () => {
expect(isDivisionTestFailed(31)).toBe(true)
expect(isDivisionTestFailed(34)).toBe(false)
})
it("canNavigateToStep uses maxReachedStep only", () => {
expect(canNavigateToStep(2, { maxReachedStep: 1, step1Paid: true })).toBe(false)
expect(canNavigateToStep(2, { maxReachedStep: 2 })).toBe(true)
expect(canNavigateToStep(3, { maxReachedStep: 2 })).toBe(false)
})
it("isStepReadOnly when viewing earlier step", () => {
expect(isStepReadOnly(1, { maxReachedStep: 2 })).toBe(true)
expect(isStepReadOnly(2, { maxReachedStep: 2 })).toBe(false)
})
it("buildStepCompletedFlags", () => {
expect(buildStepCompletedFlags(true, 2)).toEqual([true, true, false])
expect(buildStepCompletedFlags(true, 3)).toEqual([true, true, false])
expect(buildStepCompletedFlags(true, 3, true)).toEqual([true, true, true])
expect(buildStepCompletedFlags(true, 2, true)).toEqual([true, true, false])
})
it("resolveMaxReachedStepFromSubProgress", () => {
expect(resolveMaxReachedStepFromSubProgress(34)).toBe(1)
expect(resolveMaxReachedStepFromSubProgress(35)).toBe(2)
expect(resolveMaxReachedStepFromSubProgress(36)).toBe(3)
expect(resolveMaxReachedStepFromSubProgress(31, 3)).toBe(3)
expect(resolveMaxReachedStepFromSubProgress(31, 2)).toBe(2)
expect(resolveMaxReachedStepFromSubProgress(31, 1)).toBe(1)
})
it("resolveInitialWizardSteps: 31 with progress opens matching step", () => {
expect(resolveInitialWizardSteps(31, 3)).toEqual({ viewStep: 3, maxReachedStep: 3 })
expect(resolveInitialWizardSteps(31, 2)).toEqual({ viewStep: 2, maxReachedStep: 2 })
expect(resolveInitialWizardSteps(31, 1)).toEqual({ viewStep: 1, maxReachedStep: 1 })
})
it("shouldSyncWizardStepsFromProgress", () => {
expect(shouldSyncWizardStepsFromProgress(31)).toBe(true)
expect(shouldSyncWizardStepsFromProgress(36)).toBe(true)
expect(shouldSyncWizardStepsFromProgress(34)).toBe(false)
})
it("resolveInitialWizardSteps: progress takes priority over subProgress", () => {
expect(resolveInitialWizardSteps(35, 3)).toEqual({ viewStep: 3, maxReachedStep: 3 })
expect(resolveInitialWizardSteps(34, 3)).toEqual({ viewStep: 3, maxReachedStep: 3 })
expect(resolveInitialWizardSteps(36, 1)).toEqual({ viewStep: 1, maxReachedStep: 3 })
})
it("resolveInitialWizardSteps: 36 without progress falls back to step3", () => {
expect(resolveInitialWizardSteps(36)).toEqual({ viewStep: 3, maxReachedStep: 3 })
})
it("resolveInitialWizardSteps: 35 without progress defaults step1", () => {
expect(resolveInitialWizardSteps(35)).toEqual({ viewStep: 1, maxReachedStep: 2 })
expect(resolveInitialWizardSteps(35, 2)).toEqual({ viewStep: 2, maxReachedStep: 2 })
})
it("resolveInitialWizardSteps: 34 without progress stays step1", () => {
expect(resolveInitialWizardSteps(34)).toEqual({ viewStep: 1, maxReachedStep: 1 })
})
})
/**
* @jest-environment jsdom
*/
import {
filterFinancialIndicesToSubmitIncremental,
financialSnapshotEqualsBaseline,
financialTabDiffersFromBaseline,
resolveIndicesForFinancialIncrementalSubmit
} from "@/views/systemConfig/merchant/financialRules/utils/financialRulesIncrementalGate"
import { buildGoodsTypeGroupIncrementalRules } from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
const baselineRule = {
groupType: 1,
groupDivisionRuleId: "17805",
expenseCategoryRules: [
{
expenseCategoryId: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10",
children: []
}
],
merchantDistributionRules: [{ merchantId: 1, merchantName: "平台" }],
owningMerchantDistributionRules: [{ merchantId: 2, merchantName: "流量" }]
}
function makeTabs(overrides = {}) {
return [
{
name: "1",
classificationUserTouched: false,
sessionAdded: false,
...overrides
}
]
}
describe("resolveIndicesForFinancialIncrementalSubmit", () => {
test("无 touched、无 diff → 空数组", () => {
const baseline = [baselineRule]
const caches = [baselineRule]
expect(
resolveIndicesForFinancialIncrementalSubmit(makeTabs(), baseline, caches)
).toEqual([])
})
test("有基线槽位、diff 但无 touched/sessionAdded:不进入(挡无操作假脏)", () => {
const baseline = [baselineRule]
const caches = [
{
...baselineRule,
expenseCategoryRules: [
{
expenseCategoryId: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "20",
children: []
}
]
}
]
expect(
resolveIndicesForFinancialIncrementalSubmit(makeTabs(), baseline, caches)
).toEqual([])
})
test("有 touched 且 diff → 进入", () => {
const baseline = [baselineRule]
const caches = [
{
...baselineRule,
expenseCategoryRules: [
{
expenseCategoryId: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "20",
children: []
}
]
}
]
expect(
resolveIndicesForFinancialIncrementalSubmit(
makeTabs({ classificationUserTouched: true }),
baseline,
caches
)
).toEqual([0])
})
test("sessionAdded 新 Tab → 进入", () => {
const baseline = [baselineRule]
const caches = [baselineRule, { groupType: 2 }]
const tabs = [
{ name: "1", classificationUserTouched: false, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: true }
]
expect(
resolveIndicesForFinancialIncrementalSubmit(tabs, baseline, caches)
).toEqual([1])
})
})
describe("filterFinancialIndicesToSubmitIncremental", () => {
test("有 touched 但无 diff → 第一层 gate 即不进入", () => {
const baseline = [baselineRule]
expect(
resolveIndicesForFinancialIncrementalSubmit(
makeTabs({ classificationUserTouched: true }),
baseline,
[baselineRule]
)
).toEqual([])
})
test("有 touched 但快照 equals baseline → 过滤后为空", () => {
const baseline = [baselineRule]
const validatedByIndex = { 0: baselineRule }
const dirty = [0]
const tabs = makeTabs({ classificationUserTouched: true })
expect(
filterFinancialIndicesToSubmitIncremental(
dirty,
validatedByIndex,
baseline,
tabs
)
).toEqual([])
})
test("有 touched 且快照与基线不同 → 保留", () => {
const baseline = [baselineRule]
const changed = {
...baselineRule,
expenseCategoryRules: [
{
expenseCategoryId: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "99",
children: []
}
]
}
const validatedByIndex = { 0: changed }
expect(
filterFinancialIndicesToSubmitIncremental(
[0],
validatedByIndex,
baseline,
makeTabs({ classificationUserTouched: true })
)
).toEqual([0])
})
test("端到端:误 touched + 未改规则 → 不产生 UPDATE", () => {
const baseline = [baselineRule]
const validatedByIndex = { 0: baselineRule }
const dirty = resolveIndicesForFinancialIncrementalSubmit(
makeTabs({ classificationUserTouched: true }),
baseline,
[baselineRule]
)
expect(dirty).toEqual([])
const indicesToSubmit = filterFinancialIndicesToSubmitIncremental(
dirty,
validatedByIndex,
baseline,
makeTabs({ classificationUserTouched: true })
)
expect(indicesToSubmit).toEqual([])
const incremental = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
indicesToSubmit,
false
)
expect(incremental).toEqual([])
})
test("真实修改 → filter 后仍生成 UPDATE", () => {
const baseline = [baselineRule]
const changed = {
...baselineRule,
expenseCategoryRules: [
{
expenseCategoryId: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "50",
children: []
}
]
}
const validatedByIndex = { 0: changed }
const dirty = resolveIndicesForFinancialIncrementalSubmit(
makeTabs({ classificationUserTouched: true }),
baseline,
[changed]
)
const indicesToSubmit = filterFinancialIndicesToSubmitIncremental(
dirty,
validatedByIndex,
baseline,
makeTabs({ classificationUserTouched: true })
)
const incremental = buildGoodsTypeGroupIncrementalRules(
validatedByIndex,
indicesToSubmit,
false
)
expect(incremental).toHaveLength(1)
expect(incremental[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
})
})
describe("financialTabDiffersFromBaseline / financialSnapshotEqualsBaseline", () => {
test("相同规则:diff false,snapshot equals true", () => {
const baseline = [baselineRule]
expect(financialTabDiffersFromBaseline(baseline, 0, baselineRule)).toBe(false)
expect(financialSnapshotEqualsBaseline(baseline, 0, baselineRule)).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import { ensureAllCategoryRuleFirst } from "@/views/systemConfig/merchant/financialRules/utils/ensureAllCategoryRuleFirst"
import { buildGoodsTypeGroupIncrementalRules } from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
import {
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
import {
mergeActiveTabPayload,
mergePreparedWithCache,
simulateRemoveTab
} from "./helpers/financialRulesTestHelpers"
function resolveIncrementalType(preparedRule, cachedRule) {
const merged = mergeReconciliationRuleServerFields(preparedRule, cachedRule)
const idStr = getStableReconciliationRuleId(merged)
return idStr ? GOODS_TYPE_GROUP_RULE_OP.UPDATE : GOODS_TYPE_GROUP_RULE_OP.ADD
}
describe("ensureAllCategoryRuleFirst", () => {
test("空数组 → 默认 { groupType: 1 }", () => {
expect(ensureAllCategoryRuleFirst(null)).toEqual([{ groupType: 1 }])
})
test("groupType 1 已在 index 0 且带 groupDivisionRuleId 时原样保留", () => {
const rules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
]
expect(ensureAllCategoryRuleFirst(rules)).toEqual(rules)
expect(getStableReconciliationRuleId(rules[0])).toBe("17805")
})
test("首条为特殊品类、groupType 1 在后时:整条移至 index 0(保留 id)", () => {
const input = [
{ groupType: 2, groupDivisionRuleId: "sp-1" },
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
]
const out = ensureAllCategoryRuleFirst(input)
expect(out).toHaveLength(2)
expect(out[0].groupType).toBe(1)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
expect(out[1].groupType).toBe(2)
})
test("仅有特殊品类时 prepend 空壳全部品类", () => {
const out = ensureAllCategoryRuleFirst([
{ groupType: 2, groupDivisionRuleId: "sp-1" }
])
expect(out[0]).toEqual({ groupType: 1 })
expect(out[1].groupDivisionRuleId).toBe("sp-1")
})
})
describe("goodsTypeGroup ADD type reason (API 有 id)", () => {
test("Tab0 缓存有 groupDivisionRuleId 17805 → UPDATE", () => {
const rules = ensureAllCategoryRuleFirst([
{ groupType: 2, groupDivisionRuleId: "sp-1" },
{ groupType: 1, groupDivisionRuleId: 17805, groupSettleRuleId: 17942 }
])
const cached = rules[0]
const prepared = { groupType: 1, expenseCategoryRules: [{}] }
expect(resolveIncrementalType(prepared, cached)).toBe(
GOODS_TYPE_GROUP_RULE_OP.UPDATE
)
const validatedByIndex = {
0: mergePreparedWithCache(prepared, cached)
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
})
test("mergeChildClassificationPayload 保留 groupDivisionRuleId / groupSettleRuleId", () => {
const prev = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
const { next } = mergeChildClassificationPayload(
{ groupType: 1, expenseCategoryRules: [] },
prev
)
expect(next.groupDivisionRuleId).toBe(17805)
expect(next.groupSettleRuleId).toBe(17942)
})
})
describe("removeTab / getAllParams id retention", () => {
test("getAllParams merge 后 index 0 仍保留 groupDivisionRuleId", () => {
const slotCache = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
expenseCategoryRules: [{ id: 1 }]
}
const childPayload = {
groupType: 1,
expenseCategoryRules: [{ id: 1 }]
}
const merged = mergeActiveTabPayload(childPayload, slotCache)
expect(merged.groupDivisionRuleId).toBe(17805)
expect(merged.groupSettleRuleId).toBe(17942)
})
test("删 Tab 后 index 0 保留 id 且 incremental type 为 UPDATE", () => {
const prevRules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
expenseCategoryRules: []
},
{ groupType: 2, groupDivisionRuleId: 17806, groupSettleRuleId: 17943 },
{ groupType: 2, groupDivisionRuleId: 17808, groupSettleRuleId: 17944 }
]
const allParams = [
{ groupType: 1, expenseCategoryRules: [] },
{ groupType: 2, expenseCategoryRules: [] },
{ groupType: 2, expenseCategoryRules: [] }
]
const mergedAllParams = allParams.map((payload, i) => {
const { next } = mergeChildClassificationPayload(payload, prevRules[i])
return next
})
const removedTabIndex = 1
const remaining = simulateRemoveTab(mergedAllParams, prevRules, removedTabIndex)
expect(remaining).toHaveLength(2)
expect(remaining[0].groupDivisionRuleId).toBe(17805)
expect(remaining[0].groupSettleRuleId).toBe(17942)
expect(remaining[1].groupDivisionRuleId).toBe(17808)
const prepared = { groupType: 1, expenseCategoryRules: [] }
expect(resolveIncrementalType(prepared, remaining[0])).toBe(
GOODS_TYPE_GROUP_RULE_OP.UPDATE
)
const validatedByIndex = {
0: mergePreparedWithCache(prepared, remaining[0])
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
expect(out[0].groupSettleRuleId).toBe(17942)
})
test("删光特殊品类后仅剩全部品类仍带 id → UPDATE", () => {
const prevRules = [
{
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
},
{ groupType: 2, groupDivisionRuleId: 17806 },
{ groupType: 2, groupDivisionRuleId: 17808 }
]
let allParams = prevRules.map((cached) =>
mergeChildClassificationPayload(
{ groupType: cached.groupType, expenseCategoryRules: [] },
cached
).next
)
let prevCache = prevRules.slice()
allParams = simulateRemoveTab(allParams, prevCache, 2)
prevCache = simulateRemoveTab(prevCache, prevCache, 2)
allParams = simulateRemoveTab(allParams, prevCache, 1)
expect(allParams).toHaveLength(1)
expect(allParams[0].groupDivisionRuleId).toBe(17805)
const validatedByIndex = {
0: mergePreparedWithCache(
{ groupType: 1, expenseCategoryRules: [] },
allParams[0]
)
}
const out = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
expect(out[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(out[0].groupDivisionRuleId).toBe(17805)
})
})
import path from "path"
import fs from "fs"
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
import { mergeReconciliationRuleServerFields } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
import { applyRemoveTabToGoodsTypeGroupRules } from "@/views/systemConfig/merchant/financialRules/utils/applyRemoveTabToGoodsTypeGroupRules"
const FIXTURE_ROOT = path.join(__dirname, "../../../fixtures/financialRules")
/**
* 优先 real/,回退 synthetic/
* @param {string} name 不含扩展名
*/
export function loadFixture(name) {
const realPath = path.join(FIXTURE_ROOT, "real", `${name}.json`)
if (fs.existsSync(realPath)) {
return JSON.parse(fs.readFileSync(realPath, "utf8"))
}
const syntheticPath = path.join(FIXTURE_ROOT, "synthetic", `${name}.json`)
if (fs.existsSync(syntheticPath)) {
return JSON.parse(fs.readFileSync(syntheticPath, "utf8"))
}
throw new Error(`Fixture not found: ${name}`)
}
/** getAllParams 激活 Tab 分支:子组件 payload 与槽位缓存 merge */
export function mergeActiveTabPayload(childPayload, slotCache) {
const { next } = mergeChildClassificationPayload(childPayload, slotCache)
return next
}
/** removeTab 核心:splice + oldIdx 服务端 id 合并 */
export function simulateRemoveTab(rules, prevRules, removedTabIndex) {
const { remainingRules } = applyRemoveTabToGoodsTypeGroupRules({
goodsTypeGroupRules: rules,
tabIndex: removedTabIndex,
prevGoodsTypeGroupRules: prevRules,
removedRule: rules[removedTabIndex],
removedTabMeta: {},
isSessionOnlyNew: false
})
return remainingRules
}
export function mergeChildPayloadAtIndex(payload, cached) {
return mergeChildClassificationPayload(payload, cached).next
}
export function mergePreparedWithCache(prepared, cached) {
return mergeReconciliationRuleServerFields(prepared, cached)
}
/**
* @jest-environment jsdom
*/
import { mergeChildClassificationPayload } from "@/views/systemConfig/merchant/financialRules/utils/mergeClassificationPayload"
describe("mergeChildClassificationPayload", () => {
test("子组件空数组不覆盖缓存非空数组", () => {
const prev = {
expenseCategoryRules: [{ id: 1, calculateMode: 1 }],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "100" }],
goodsTypes: [{ goodsType: "G1" }]
}
const { next } = mergeChildClassificationPayload(
{
expenseCategoryRules: [],
merchantDistributionRules: [],
owningMerchantDistributionRules: [],
goodsTypes: []
},
prev
)
expect(next.expenseCategoryRules).toEqual(prev.expenseCategoryRules)
expect(next.merchantDistributionRules).toEqual(prev.merchantDistributionRules)
expect(next.owningMerchantDistributionRules).toEqual(prev.owningMerchantDistributionRules)
expect(next.goodsTypes).toEqual(prev.goodsTypes)
})
test("payload 未带 expenseCategoryRules → 保留 base", () => {
const prev = { expenseCategoryRules: [{ id: 1 }] }
const { next } = mergeChildClassificationPayload({ groupType: 1 }, prev)
expect(next.expenseCategoryRules).toEqual(prev.expenseCategoryRules)
})
test("payload 带非空 expenseCategoryRules → 覆盖", () => {
const prev = { expenseCategoryRules: [{ id: 1 }] }
const incoming = [{ id: 2, calculateMode: 1 }]
const { next } = mergeChildClassificationPayload(
{ expenseCategoryRules: incoming },
prev
)
expect(next.expenseCategoryRules).toEqual(incoming)
})
test("保留 SERVER_ID_FIELDS", () => {
const prev = {
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
id: "x"
}
const { next } = mergeChildClassificationPayload({ groupType: 1 }, prev)
expect(next.groupDivisionRuleId).toBe(17805)
expect(next.groupSettleRuleId).toBe(17942)
expect(next.id).toBe("x")
})
})
import {
FORCE_DIVISION_TEST_SUB_PROGRESS,
applyDivisionRuleTestGetMock,
mockDivisionRuleTestGetSubProgress
} from '@/api/mockDivisionRuleTestGetResponse'
describe('mockDivisionRuleTestGetSubProgress', () => {
it('applyDivisionRuleTestGetMock passes through when mock disabled', () => {
const raw = { subProgress: 10 }
expect(applyDivisionRuleTestGetMock(raw)).toBe(raw)
expect(applyDivisionRuleTestGetMock(raw).subProgress).toBe(10)
})
it('forces root and nested subProgress to 35', () => {
const raw = {
subProgress: 10,
divisionRuleTestItem: { subProgress: 20, orderCode: 'O1' },
divisionRuleTests: [
{
paymentChannelId: 1,
subProgress: 30,
divisionRuleTestItem: { subProgress: 31 }
}
]
}
const out = mockDivisionRuleTestGetSubProgress(raw)
expect(out.subProgress).toBe(FORCE_DIVISION_TEST_SUB_PROGRESS)
expect(out.divisionRuleTestItem.subProgress).toBe(35)
expect(out.divisionRuleTests[0].subProgress).toBe(35)
expect(out.divisionRuleTests[0].divisionRuleTestItem.subProgress).toBe(35)
expect(out.divisionRuleTestItem.orderCode).toBe('O1')
})
it('returns nullish as-is', () => {
expect(mockDivisionRuleTestGetSubProgress(null)).toBe(null)
expect(mockDivisionRuleTestGetSubProgress(undefined)).toBe(undefined)
})
})
/**
* @jest-environment jsdom
*/
import { normalizeRuleGoodsTypesForCategory } from "@/views/systemConfig/merchant/financialRules/utils/normalizeRuleGoodsTypesForCategory"
describe("normalizeRuleGoodsTypesForCategory", () => {
test("categoryType 1: clones goodsTypes and clears upgrade/package slots", () => {
const item = {
goodsTypes: [{ categoryType: 1, goodsType: 10, goodsTypeName: "A" }]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(1)
expect(item.goodsTypes).toHaveLength(1)
expect(item.goodsTypes[0].goodsType).toBe(10)
expect(item.upgradeGoods).toEqual([])
expect(item.packageGoods).toEqual([])
expect(upgradeArr).toHaveLength(0)
expect(packageArr).toHaveLength(0)
})
test("categoryType 2: moves to upgradeGoods and collects upgradeArr", () => {
const item = {
goodsTypes: [
{
categoryType: 2,
upgradeGoodsId: "u1",
upgradeGoodsName: "U",
commodityCode: "C1",
merchantGoodsCode: "M1"
}
]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(2)
expect(item.goodsTypes).toEqual([])
expect(item.upgradeGoods).toHaveLength(1)
expect(upgradeArr).toEqual([
{
upgradeGoodsId: "u1",
upgradeGoodsName: "U",
commodityCode: "C1",
merchantGoodsCode: "M1"
}
])
expect(packageArr).toHaveLength(0)
})
test("categoryType 3: moves to packageGoods and collects packageArr", () => {
const item = {
goodsTypes: [
{ categoryType: 3, packageCode: "p1", packageName: "Pkg" }
]
}
const upgradeArr = []
const packageArr = []
normalizeRuleGoodsTypesForCategory(item, upgradeArr, packageArr)
expect(item.categoryType).toBe(3)
expect(item.goodsTypes).toEqual([])
expect(item.packageGoods).toHaveLength(1)
expect(packageArr).toEqual([{ packageCode: "p1", packageName: "Pkg" }])
expect(upgradeArr).toHaveLength(0)
})
test("no goodsTypes: no-op", () => {
const item = {}
normalizeRuleGoodsTypesForCategory(item, [], [])
expect(item).toEqual({})
})
})
import {
getStableReconciliationRuleId,
mergeReconciliationRuleServerFields
} from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationIncrementalRules"
describe("getStableReconciliationRuleId", () => {
test("优先 groupDivisionRuleId", () => {
expect(getStableReconciliationRuleId({ groupDivisionRuleId: 17805 })).toBe("17805")
expect(getStableReconciliationRuleId({ groupDivisionRuleId: "17805" })).toBe("17805")
})
test("groupDivisionRuleId 空时 fallback id", () => {
expect(getStableReconciliationRuleId({ id: 99 })).toBe("99")
expect(getStableReconciliationRuleId({ groupDivisionRuleId: "", id: "abc" })).toBe("abc")
})
test("无效输入 → 空字符串", () => {
expect(getStableReconciliationRuleId(null)).toBe("")
expect(getStableReconciliationRuleId({})).toBe("")
})
})
describe("mergeReconciliationRuleServerFields", () => {
test("prepared 无 id、cached 有 id → 保留", () => {
const prepared = { groupType: 1, expenseCategoryRules: [] }
const cached = {
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942,
id: "server-id"
}
const out = mergeReconciliationRuleServerFields(prepared, cached)
expect(out.groupDivisionRuleId).toBe(17805)
expect(out.groupSettleRuleId).toBe(17942)
expect(out.id).toBe("server-id")
expect(out.groupType).toBe(1)
})
test("cached 有 id 时合并进 prepared", () => {
const prepared = { groupType: 1 }
const cached = { groupDivisionRuleId: "old" }
const out = mergeReconciliationRuleServerFields(prepared, cached)
expect(out.groupDivisionRuleId).toBe("old")
})
test("无 cached → 原样返回", () => {
const prepared = { groupType: 1 }
expect(mergeReconciliationRuleServerFields(prepared, null)).toEqual(prepared)
})
})
/**
* @jest-environment jsdom
*/
import {
appendDeleteOpsToIncremental,
buildGoodsTypeGroupIncrementalRules
} from "@/views/systemConfig/merchant/financialRules/utils/buildGoodsTypeGroupIncrementalRules"
import {
applyRemoveTabToGoodsTypeGroupRules,
collectPendingDeleteForRemovedTab,
mapTabMetaAfterTabRemoval
} from "@/views/systemConfig/merchant/financialRules/utils/applyRemoveTabToGoodsTypeGroupRules"
import { GOODS_TYPE_GROUP_RULE_OP } from "@/views/systemConfig/merchant/financialRules/utils/goodsTypeGroupRuleOpType"
import {
loadFixture,
mergeActiveTabPayload,
mergeChildPayloadAtIndex,
mergePreparedWithCache,
simulateRemoveTab
} from "./helpers/financialRulesTestHelpers"
describe("collectPendingDeleteForRemovedTab", () => {
test("sessionAdded Tab → 不产生 pendingDelete", () => {
expect(
collectPendingDeleteForRemovedTab({
removedRule: { groupType: 2 },
removedTabMeta: { sessionAdded: true },
isSessionOnlyNew: true
})
).toBeNull()
})
test("有 groupDivisionRuleId → 返回快照", () => {
const snap = collectPendingDeleteForRemovedTab({
removedRule: { groupType: 2, groupDivisionRuleId: 17806 },
removedTabMeta: {},
isSessionOnlyNew: false
})
expect(snap.groupDivisionRuleId).toBe(17806)
expect(snap.type).toBeUndefined()
})
})
describe("mapTabMetaAfterTabRemoval", () => {
test("删中间 Tab → revision/touched 按 oldIdx 映射", () => {
const prevTabsMeta = [
{ sessionAdded: false, ruleCacheRevision: 1, confirmedRuleCacheRevision: 1, classificationUserTouched: false },
{ sessionAdded: false, ruleCacheRevision: 5, confirmedRuleCacheRevision: 3, classificationUserTouched: true },
{ sessionAdded: true, ruleCacheRevision: 0, confirmedRuleCacheRevision: 0, classificationUserTouched: false }
]
const out = mapTabMetaAfterTabRemoval(prevTabsMeta, 1, 2)
expect(out[0].ruleCacheRevision).toBe(1)
expect(out[1].ruleCacheRevision).toBe(0)
expect(out[1].sessionAdded).toBe(true)
expect(out[1].classificationUserTouched).toBe(false)
})
})
describe("removeTab full chain", () => {
test("删 Tab 后 appendDeleteOpsToIncremental:UPDATE + DELETE", () => {
const fixture = loadFixture("all-plus-special-tabs")
const prevRules = fixture.goodsTypeGroupRules
let allParams = prevRules.map((cached) =>
mergeChildPayloadAtIndex(
{ groupType: cached.groupType, expenseCategoryRules: cached.expenseCategoryRules || [] },
cached
)
)
const pendingDeletes = []
let prevCache = prevRules.slice()
for (const tabIndex of [2, 1]) {
const removedRule = allParams[tabIndex]
const { remainingRules, pendingDelete } = applyRemoveTabToGoodsTypeGroupRules({
goodsTypeGroupRules: allParams,
tabIndex,
prevGoodsTypeGroupRules: prevCache,
removedRule,
removedTabMeta: { sessionAdded: false },
isSessionOnlyNew: false
})
if (pendingDelete) pendingDeletes.push(pendingDelete)
allParams = remainingRules
prevCache = simulateRemoveTab(prevCache, prevCache, tabIndex)
}
expect(allParams).toHaveLength(1)
expect(allParams[0].groupDivisionRuleId).toBe(17805)
const validatedByIndex = {
0: mergePreparedWithCache(allParams[0], allParams[0])
}
const incremental = buildGoodsTypeGroupIncrementalRules(validatedByIndex, [0], false)
const submit = appendDeleteOpsToIncremental(incremental, pendingDeletes)
expect(submit[0].type).toBe(GOODS_TYPE_GROUP_RULE_OP.UPDATE)
expect(submit[0].groupDivisionRuleId).toBe(17805)
const deleteIds = submit
.filter((r) => r.type === GOODS_TYPE_GROUP_RULE_OP.DELETE)
.map((r) => r.groupDivisionRuleId)
expect(deleteIds).toEqual(expect.arrayContaining(["17806", "17808"]))
})
test("getAllParams merge 后 index 0 仍保留 id", () => {
const slotCache = {
groupType: 1,
groupDivisionRuleId: 17805,
groupSettleRuleId: 17942
}
const merged = mergeActiveTabPayload({ groupType: 1 }, slotCache)
expect(merged.groupDivisionRuleId).toBe(17805)
})
})
import { resolveDivisionRuleIdFromApi } from "@/views/systemConfig/merchant/financialRules/utils/resolveDivisionRuleIdFromApi"
describe("resolveDivisionRuleIdFromApi", () => {
it("returns top-level divisionRuleId", () => {
expect(resolveDivisionRuleIdFromApi({ divisionRuleId: 4928 })).toBe(4928)
expect(resolveDivisionRuleIdFromApi({ divisionRuleId: "rule-1" })).toBe("rule-1")
})
it("returns undefined for missing or empty id", () => {
expect(resolveDivisionRuleIdFromApi(null)).toBeUndefined()
expect(resolveDivisionRuleIdFromApi({})).toBeUndefined()
expect(resolveDivisionRuleIdFromApi({ divisionRuleId: "" })).toBeUndefined()
})
it("falls back to merchantSettleDistributeRule.divisionRuleId", () => {
expect(
resolveDivisionRuleIdFromApi({
merchantSettleDistributeRule: { divisionRuleId: 9001 }
})
).toBe(9001)
})
it("prefers top-level divisionRuleId over nested", () => {
expect(
resolveDivisionRuleIdFromApi({
divisionRuleId: 100,
merchantSettleDistributeRule: { divisionRuleId: 200 }
})
).toBe(100)
})
})
import {
resolveDivisionTestOrderCode,
resolveDivisionTestOutTradeNo,
resolveDivisionTestSubProgress,
resolveDivisionTestMerchantDivisions,
resolveGoodsTypeGroupDivisionId,
resolveDivisionTestProgress,
normalizeDivisionTestPayload
} from "@/views/systemConfig/merchant/financialRules/utils/resolveDivisionTestOrderCode"
describe("resolveDivisionTestOrderCode", () => {
it("reads orderCode from divisionRuleTests[].divisionRuleTestItem", () => {
const code = resolveDivisionTestOrderCode({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { orderCode: "ORD001" }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { orderCode: "ORD002" }
}
]
})
expect(code).toBe("ORD002")
})
it("reads from top-level divisionRuleTestItem", () => {
expect(
resolveDivisionTestOrderCode({
divisionRuleTestItem: { orderCode: "ORD003" }
})
).toBe("ORD003")
})
it("reads outTradeNo from divisionRuleTests[].divisionRuleTestItem", () => {
expect(
resolveDivisionTestOutTradeNo({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { outTradeNo: "OUT001" }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { outTradeNo: "OUT002" }
}
]
})
).toBe("OUT002")
})
it("normalizeDivisionTestPayload sets outTradeNo on root", () => {
const payload = normalizeDivisionTestPayload({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { outTradeNo: "OUT003" }
}
]
})
expect(payload.outTradeNo).toBe("OUT003")
})
it("normalizeDivisionTestPayload sets orderCode on root", () => {
const payload = normalizeDivisionTestPayload({
divisionRuleTests: [
{ divisionRuleTestItem: { orderCode: "ORD004" } }
]
})
expect(payload.orderCode).toBe("ORD004")
})
it("resolveDivisionTestMerchantDivisions from divisionRuleTestItem", () => {
const list = resolveDivisionTestMerchantDivisions({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: {
testMerchantDivisions: [{ merchantName: "A" }]
}
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: {
testMerchantDivisions: [
{ merchantName: "B", distributionMoney: "1" }
]
}
}
]
})
expect(list).toHaveLength(1)
expect(list[0].merchantName).toBe("B")
expect(list[0].distributionMoney).toBe("1")
})
it("normalizeDivisionTestPayload sets testMerchantDivisions", () => {
const payload = normalizeDivisionTestPayload({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: {
testMerchantDivisions: [{ merchantName: "X" }]
}
}
]
})
expect(payload.testMerchantDivisions).toHaveLength(1)
expect(payload.testMerchantDivisions[0].merchantName).toBe("X")
})
it("resolveDivisionTestSubProgress from divisionRuleTestItem", () => {
expect(
resolveDivisionTestSubProgress({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { subProgress: 35 }
}
]
})
).toBe(35)
})
it("resolveGoodsTypeGroupDivisionId from divisionRuleTests channel entry", () => {
expect(
resolveGoodsTypeGroupDivisionId({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { goodsTypeGroupDivisionId: 100 }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { goodsTypeGroupDivisionId: 200 }
}
]
})
).toBe(200)
})
it("resolveGoodsTypeGroupDivisionId from top-level divisionRuleTestItem", () => {
expect(
resolveGoodsTypeGroupDivisionId({
divisionRuleTestItem: { goodsTypeGroupDivisionId: 300 }
})
).toBe(300)
})
it("resolveGoodsTypeGroupDivisionId from root", () => {
expect(
resolveGoodsTypeGroupDivisionId({ goodsTypeGroupDivisionId: 400 })
).toBe(400)
})
it("resolveDivisionTestProgress from divisionRuleTests channel entry", () => {
expect(
resolveDivisionTestProgress({
paymentChannelId: "ch2",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { progress: 1 }
},
{
paymentChannelId: "ch2",
divisionRuleTestItem: { progress: 2 }
}
]
})
).toBe(2)
})
it("normalizeDivisionTestPayload sets progress on root", () => {
const payload = normalizeDivisionTestPayload({
paymentChannelId: "ch1",
divisionRuleTests: [
{
paymentChannelId: "ch1",
divisionRuleTestItem: { progress: 3 }
}
]
})
expect(payload.progress).toBe(3)
})
})
import { resolveIndicesForGoodsTypeGroupValidation } from "@/views/systemConfig/merchant/financialRules/utils/resolveIndicesForGoodsTypeGroupValidation"
describe("resolveIndicesForGoodsTypeGroupValidation", () => {
test("onlyActiveTab: mirrors indicesForIncremental (single current tab)", () => {
const allRuleTabIndices = [0, 1, 2]
expect(
resolveIndicesForGoodsTypeGroupValidation({
onlyActiveTab: true,
indicesForIncremental: [1],
allRuleTabIndices,
activeDivisionTabIndex: 1
})
).toEqual([1])
})
test("onlyActiveTab: does not expand to allRuleTabIndices when multiple tabs exist", () => {
const allRuleTabIndices = [0, 1, 2, 3]
const out = resolveIndicesForGoodsTypeGroupValidation({
onlyActiveTab: true,
indicesForIncremental: [2],
allRuleTabIndices,
activeDivisionTabIndex: 2
})
expect(out).toHaveLength(1)
expect(out[0]).toBe(2)
})
test("full submit: validates all tabs with active tab first when active is in list", () => {
expect(
resolveIndicesForGoodsTypeGroupValidation({
onlyActiveTab: false,
indicesForIncremental: [0],
allRuleTabIndices: [0, 1, 2],
activeDivisionTabIndex: 1
})
).toEqual([1, 0, 2])
})
test("full submit: sorts when active index not applicable", () => {
const allRuleTabIndices = [2, 0, 1]
expect(
resolveIndicesForGoodsTypeGroupValidation({
onlyActiveTab: false,
indicesForIncremental: [],
allRuleTabIndices,
activeDivisionTabIndex: -1
})
).toEqual([0, 1, 2])
})
test("full submit: single tab unchanged", () => {
expect(
resolveIndicesForGoodsTypeGroupValidation({
onlyActiveTab: false,
indicesForIncremental: [],
allRuleTabIndices: [2],
activeDivisionTabIndex: 100
})
).toEqual([2])
})
})
import { resolveIndicesForIncrementalSubmit } from "@/views/systemConfig/merchant/financialRules/utils/resolveIndicesForIncrementalSubmit"
describe("resolveIndicesForIncrementalSubmit", () => {
test("无 touched/sessionAdded → 空数组", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: false, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: false }
])
).toEqual([])
})
test("touched Tab 进入", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: true, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: false }
])
).toEqual([0])
})
test("sessionAdded Tab 进入", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "1", classificationUserTouched: false, sessionAdded: false },
{ name: "2", classificationUserTouched: false, sessionAdded: true }
])
).toEqual([1])
})
test("排除 name=add", () => {
expect(
resolveIndicesForIncrementalSubmit([
{ name: "add", classificationUserTouched: true, sessionAdded: true }
])
).toEqual([])
})
})
import {
sortDivisionTestMerchants,
isPlatformMerchant
} from "@/views/systemConfig/merchant/financialRules/utils/sortDivisionTestMerchants"
describe("sortDivisionTestMerchants", () => {
it("sorts by targetMerchantType desc 3, 2, 1", () => {
const list = [
{ merchantName: "平台", targetMerchantType: 1 },
{ merchantName: "4s店", targetMerchantType: 3 },
{ merchantName: "服务商", targetMerchantType: 2 }
]
const sorted = sortDivisionTestMerchants(list)
expect(sorted.map((m) => m.merchantName)).toEqual(["4s店", "服务商", "平台"])
})
it("items without targetMerchantType sort after known types", () => {
const list = [
{ merchantName: "未知", targetType: 1 },
{ merchantName: "4s店", targetMerchantType: 3 }
]
const sorted = sortDivisionTestMerchants(list)
expect(sorted.map((m) => m.merchantName)).toEqual(["4s店", "未知"])
})
it("isPlatformMerchant", () => {
expect(isPlatformMerchant({ targetMerchantType: 1 })).toBe(true)
expect(isPlatformMerchant({ targetMerchantType: 4 })).toBe(true)
expect(isPlatformMerchant({ targetMerchantType: 3 })).toBe(false)
expect(isPlatformMerchant({ targetType: 4 })).toBe(true)
expect(isPlatformMerchant({ targetType: 1 })).toBe(false)
})
})
/**
* @jest-environment jsdom
*/
import {
distributionRulesLookComplete,
distributionRulesConsistentWithLedgerParty,
extractServiceMerchantIdsFromExpenseCategoryRules,
ledgerMerchantIdLooseEqual,
prepareRuleForValidation,
validateGoodsTypeGroupRulePayload
} from "@/views/systemConfig/merchant/financialRules/utils/validateGoodsTypeGroupRulePayload"
function minimalValidRule(overrides = {}) {
return {
groupType: 1,
shop4sDeductChargeFlag: "Y",
partnerDeductChargeFlag: "Y",
goodsCostFlag: "N",
virtualAccountCostFlag: "N",
recoveryCostFlag: "N",
djCostFlag: "N",
thirdPartyCostFlag: "N",
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10"
}
],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "100" }],
...overrides
}
}
describe("distributionRulesLookComplete", () => {
test("完整分账表 → true", () => {
expect(distributionRulesLookComplete(minimalValidRule())).toBe(true)
})
test("空表或缺 merchantId → false", () => {
expect(
distributionRulesLookComplete({
merchantDistributionRules: [],
owningMerchantDistributionRules: [{ merchantId: "1" }]
})
).toBe(false)
expect(
distributionRulesLookComplete({
merchantDistributionRules: [{ merchantId: "" }],
owningMerchantDistributionRules: [{ merchantId: "1" }]
})
).toBe(false)
expect(distributionRulesLookComplete({})).toBe(false)
})
})
describe("ledgerMerchantIdLooseEqual", () => {
test("number / string 同值", () => {
expect(ledgerMerchantIdLooseEqual(100, "100")).toBe(true)
expect(ledgerMerchantIdLooseEqual("100", 100)).toBe(true)
})
test("不等 → false", () => {
expect(ledgerMerchantIdLooseEqual(100, 200)).toBe(false)
})
})
describe("extractServiceMerchantIdsFromExpenseCategoryRules", () => {
test("解析 targetMerchant / targetMerchantId", () => {
const ids = extractServiceMerchantIdsFromExpenseCategoryRules([
{ targetMerchant: { merchantId: "200" } },
{
formType: 2,
children: [{ targetMerchantId: "300" }]
}
])
expect(ids).toEqual(["200", "300"])
})
})
describe("distributionRulesConsistentWithLedgerParty", () => {
const ledger = {
realityPlatformMerchantId: "100",
realityShopMerchantId: "200",
djzhySubMerchantId: "300"
}
test("merchantId 在 ledger + expense 允许集合内 → true", () => {
const rule = minimalValidRule({
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10",
targetMerchantId: "400"
}
],
merchantDistributionRules: [{ merchantId: "100" }],
owningMerchantDistributionRules: [{ merchantId: "400" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(true)
})
test("merchantId 不在允许集合 → false", () => {
const rule = minimalValidRule({
merchantDistributionRules: [{ merchantId: "999" }],
owningMerchantDistributionRules: [{ merchantId: "999" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(false)
})
test("targetMerchantType===3 须等于 realityShopMerchantId", () => {
const rule = minimalValidRule({
merchantDistributionRules: [{ merchantId: "200", targetMerchantType: 3 }],
owningMerchantDistributionRules: [{ merchantId: "100" }]
})
expect(distributionRulesConsistentWithLedgerParty(rule, ledger)).toBe(true)
const bad = minimalValidRule({
merchantDistributionRules: [{ merchantId: "100", targetMerchantType: 3 }],
owningMerchantDistributionRules: [{ merchantId: "100" }]
})
expect(distributionRulesConsistentWithLedgerParty(bad, ledger)).toBe(false)
})
})
describe("validateGoodsTypeGroupRulePayload", () => {
test("最小合法 rule → true", () => {
expect(validateGoodsTypeGroupRulePayload(minimalValidRule())).toBe(true)
})
test("缺 expense 必填 → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
expenseCategoryRules: [{ calculateMode: 1 }]
})
)
).toBe(false)
})
test("formType=2 子行缺 value → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
expenseCategoryRules: [
{
calculateMode: 1,
expenseCategoryCalculateType: 1,
expenseCategoryValue: "10",
formType: 2,
children: [{ calculateMode: 1, expenseCategoryCalculateType: 1 }]
}
]
})
)
).toBe(false)
})
test("goodsCostFlag=Y 缺 convertRate → false", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({ goodsCostFlag: "Y" })
)
).toBe(false)
})
test("特殊品类 DJ 须 goodsTypeGroupRelations", () => {
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
groupType: 2,
goodsSource: 1,
goodsTypeGroupRelations: []
})
)
).toBe(false)
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
groupType: 2,
goodsSource: 1,
goodsTypeGroupRelations: [{ goodsType: "G1" }]
})
)
).toBe(true)
})
test("传入 ledgerContext 时分账行须一致", () => {
const ledger = { realityPlatformMerchantId: "100", realityShopMerchantId: "200" }
expect(validateGoodsTypeGroupRulePayload(minimalValidRule(), ledger)).toBe(true)
expect(
validateGoodsTypeGroupRulePayload(
minimalValidRule({
merchantDistributionRules: [{ merchantId: "999" }],
owningMerchantDistributionRules: [{ merchantId: "999" }]
}),
ledger
)
).toBe(false)
})
})
describe("prepareRuleForValidation", () => {
test("返回 fillDj 后的 clone", () => {
const raw = minimalValidRule({ groupType: 1 })
const prepared = prepareRuleForValidation(raw)
expect(prepared).not.toBe(raw)
expect(prepared.groupType).toBe(1)
})
})
import {
validateStep3Amounts,
isValidAmountInput,
buildStep3SubmitMerchants,
mergeStep3FormMerchants,
isMerchantCompletedFromDetail,
getStep3PendingMerchants
} from "@/views/systemConfig/merchant/financialRules/utils/validateStep3Amounts"
describe("validateStep3Amounts", () => {
it("isValidAmountInput", () => {
expect(isValidAmountInput("3.5")).toBe(true)
expect(isValidAmountInput("0")).toBe(true)
expect(isValidAmountInput("3.555")).toBe(false)
expect(isValidAmountInput("4")).toBe(false)
expect(isValidAmountInput("")).toBe(false)
})
it("isMerchantCompletedFromDetail only when detail distributionMoney is 0", () => {
expect(isMerchantCompletedFromDetail({ distributionMoney: 0 })).toBe(true)
expect(isMerchantCompletedFromDetail({ distributionMoney: "0" })).toBe(true)
expect(isMerchantCompletedFromDetail({ distributionMoney: "" })).toBe(false)
expect(isMerchantCompletedFromDetail({ distributionMoney: null })).toBe(false)
expect(isMerchantCompletedFromDetail({ distributionMoney: "1.2" })).toBe(false)
})
it("validateStep3Amounts allows confirmDivisionMoney 0 for pending merchants", () => {
const r = validateStep3Amounts([
{ distributionMoney: "0" },
{ distributionMoney: "1.2", confirmDivisionMoney: "0" }
])
expect(r.valid).toBe(true)
expect(getStep3PendingMerchants([
{ distributionMoney: "0" },
{ distributionMoney: "1.2" }
])).toHaveLength(1)
})
it("validateStep3Amounts requires pending fields", () => {
const r = validateStep3Amounts([
{ testCompleted: false, confirmDivisionMoney: "" }
])
expect(r.valid).toBe(false)
})
it("mergeStep3FormMerchants keeps user-filled amounts when props refresh", () => {
const prev = [
{ merchantId: "m1", confirmDivisionMoney: "1.5" },
{ merchantId: "m2", confirmDivisionMoney: "2.0" }
]
const next = [
{ merchantId: "m1", merchantName: "A", confirmDivisionMoney: "" },
{ merchantId: "m2", merchantName: "B", testCompleted: true }
]
const merged = mergeStep3FormMerchants(next, prev)
expect(merged[0].confirmDivisionMoney).toBe("1.5")
expect(merged[1].confirmDivisionMoney).toBe("2.0")
})
it("buildStep3SubmitMerchants merges confirmDivisionMoney into raw API list", () => {
const rawList = [
{ merchantId: "m1", merchantName: "A", distributionMoney: "1.2" }
]
const form = [
{ merchantId: "m1", confirmDivisionMoney: "1.5" }
]
const out = buildStep3SubmitMerchants(rawList, form)
expect(out).toHaveLength(1)
expect(out[0].distributionMoney).toBe("1.2")
expect(out[0].confirmDivisionMoney).toBe("1.5")
expect(out[0].testCompleted).toBeUndefined()
})
it("buildStep3SubmitMerchants excludes detail-0 only, keeps user input 0", () => {
const rawList = [
{ merchantId: "m1", distributionMoney: "0" },
{ merchantId: "m2", distributionMoney: "1.2" },
{ merchantId: "m3", distributionMoney: null }
]
const form = [
{ merchantId: "m1", confirmDivisionMoney: "9" },
{ merchantId: "m2", confirmDivisionMoney: "0" },
{ merchantId: "m3", confirmDivisionMoney: "0" }
]
const out = buildStep3SubmitMerchants(rawList, form)
expect(out).toHaveLength(2)
expect(out.map((m) => m.merchantId)).toEqual(["m2", "m3"])
expect(out[0].confirmDivisionMoney).toBe("0")
expect(out[1].confirmDivisionMoney).toBe("0")
})
})
/**
* @jest-environment jsdom
*/
import { getEffectivePhantomFullCategoryRuleRaw } from "@/views/systemConfig/merchant/merchantStep/utils/effectivePhantomReconciliationRule"
describe("getEffectivePhantomFullCategoryRuleRaw", () => {
it("prefers live phantom over baseline", () => {
const live = { id: "1", groupType: 1 }
const base = { id: "2", groupType: 2 }
expect(getEffectivePhantomFullCategoryRuleRaw(live, base)).toBe(live)
})
it("falls back to baseline when live is null", () => {
const base = { expenseCategoryRules: [] }
expect(getEffectivePhantomFullCategoryRuleRaw(null, base)).toBe(base)
})
it("returns null when both missing", () => {
expect(getEffectivePhantomFullCategoryRuleRaw(null, null)).toBe(null)
expect(getEffectivePhantomFullCategoryRuleRaw(undefined, undefined)).toBe(
null
)
})
it("ignores non-object live", () => {
const base = { a: 1 }
expect(getEffectivePhantomFullCategoryRuleRaw("x", base)).toBe(base)
})
})
/**
* @jest-environment jsdom
*/
import { normalizeReconciliationRuleForCompare } from "@/views/systemConfig/merchant/merchantStep/utils/normalizeReconciliationRuleForCompare"
import { fillDjGoodsTypeGroupRelations } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationShared"
import { financialRulePayloadDeepEqual } from "@/views/systemConfig/merchant/financialRules/utils/rulePayloadCanonicalCompare"
describe("normalizeReconciliationRuleForCompare", () => {
test("aligns form snapshot with API baseline: strip merchant, empty categoryType", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryName: "阳光激励费2",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
formType: 1,
calculateMode: 1,
nodeType: 1,
children: []
}
],
upgradeGoods: [],
packageGoods: [],
goodsTypeGroupRelations: [],
id: 26380
}
const formLikeSnapshot = {
groupType: 1,
categoryType: "",
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryName: "阳光激励费2",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
calculateMode: 1,
nodeType: 1,
children: []
}
],
upgradeGoods: [],
packageGoods: [],
goodsTypeGroupRelations: [],
id: 26380
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...formLikeSnapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("ignores API-only top-level noise keys when comparing to form snapshot", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
id: 26380,
createTime: "2024-01-01",
revision: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
formType: 1,
nodeType: 1
}
]
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
nodeType: 1
}
]
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("baseline groupDivisionRuleId only vs snapshot id only", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
groupDivisionRuleId: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
formType: 1,
nodeType: 1
}
]
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 26380,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryValue: 10,
merchant: {},
formType: 1,
nodeType: 1,
children: []
}
]
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
test("expenseCategoryRules different order compares equal when forCompare default", () => {
const rowsA = [
{
targetType: 1,
expenseCategoryId: 902,
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
calculateMode: 1,
formType: 1,
nodeType: 1
},
{
targetType: 3,
expenseCategoryId: 900,
expenseCategoryCalculateType: 3,
expenseCategoryValue: 0,
calculateMode: 1,
formType: 1,
nodeType: 1
}
]
const rowsB = [rowsA[1], rowsA[0]]
const baseline = {
groupType: 1,
goodsSource: 1,
id: 1,
expenseCategoryRules: rowsA
}
const snapshot = {
groupType: 1,
goodsSource: 1,
id: 1,
expenseCategoryRules: rowsB
}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
expect(a.expenseCategoryRules[0].expenseCategoryId).toBe(902)
expect(a.expenseCategoryRules[1].expenseCategoryId).toBe(900)
})
test("forCompare false preserves expense row order", () => {
const rowsB = [
{
targetType: 3,
expenseCategoryId: 900,
formType: 1,
nodeType: 1
},
{
targetType: 1,
expenseCategoryId: 902,
formType: 1,
nodeType: 1
}
]
const out = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({
groupType: 1,
goodsSource: 1,
expenseCategoryRules: rowsB
}),
{ forCompare: false }
)
expect(out.expenseCategoryRules[0].expenseCategoryId).toBe(900)
expect(out.expenseCategoryRules[1].expenseCategoryId).toBe(902)
})
test("strips merchant from nested children for compare", () => {
const baseline = {
groupType: 2,
goodsSource: 1,
categoryType: 1,
expenseCategoryRules: [
{
formType: 2,
nodeType: 1,
children: [
{ expenseCategoryValue: 1, targetType: 1, nodeType: 1 }
]
}
],
goodsTypeGroupRelations: [{ categoryType: 1, goodsType: 1 }]
}
const snapshot = JSON.parse(JSON.stringify(baseline))
snapshot.expenseCategoryRules[0].children[0].merchant = {}
const a = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...baseline })
)
const b = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations({ ...snapshot })
)
expect(financialRulePayloadDeepEqual(a, b)).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import {
getReconciliationRuleValidationResult,
reconciliationRulePayloadIsSubstantive
} from "@/views/systemConfig/merchant/merchantStep/utils/validateReconciliationRulePayload"
import { normalizeReconciliationRuleForCompare } from "@/views/systemConfig/merchant/merchantStep/utils/normalizeReconciliationRuleForCompare"
import { financialRulePayloadDeepEqual } from "@/views/systemConfig/merchant/financialRules/utils/rulePayloadCanonicalCompare"
import { fillDjGoodsTypeGroupRelations } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationShared"
import { deepClone } from "@/common/util"
const minimalSubstantiveRule = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [
{
targetType: 1,
expenseCategoryId: 1,
expenseCategoryName: "A",
expenseCategoryCalculateType: 3,
expenseCategoryValue: 10,
formType: 1,
calculateMode: 1,
nodeType: 1
}
],
goodsTypeGroupRelations: []
}
describe("getReconciliationRuleValidationResult", () => {
test("ok for same minimal rule as isSubstantive", () => {
const r = getReconciliationRuleValidationResult(minimalSubstantiveRule)
expect(r.ok).toBe(true)
})
test("empty object is not ok", () => {
const r = getReconciliationRuleValidationResult({})
expect(r.ok).toBe(false)
})
test("groupType 2 without goodsSource fails with prop goodsSource", () => {
const r = getReconciliationRuleValidationResult({
groupType: 2,
expenseCategoryRules: deepClone(minimalSubstantiveRule.expenseCategoryRules)
})
expect(r.ok).toBe(false)
expect(r.fieldProp).toBe("goodsSource")
})
test("groupType 1 can omit goodsSource when expense is valid", () => {
const { goodsSource, ...noGs } = minimalSubstantiveRule
const r = getReconciliationRuleValidationResult(noGs)
expect(r.ok).toBe(true)
})
})
describe("reconciliationRulePayloadIsSubstantive", () => {
test("empty or non-rule object is not substantive", () => {
expect(reconciliationRulePayloadIsSubstantive({})).toBe(false)
expect(reconciliationRulePayloadIsSubstantive(null)).toBe(false)
})
test("valid minimal all-category rule is substantive", () => {
expect(reconciliationRulePayloadIsSubstantive(minimalSubstantiveRule)).toBe(
true
)
})
})
/**
* 与 merchantCheck.reconciliationTabDiffersFromBaseline 在「无基线槽位 / 无 phantom」时一致:仅当可保存才视为相对「无基线」有差异。
*/
describe("reconciliation no-baseline empty shell", () => {
function differsWhenNoPrevRaw(cur) {
if (!cur) return false
return reconciliationRulePayloadIsSubstantive(cur)
}
test("new slot {} does not count as diff vs missing baseline", () => {
const cur = fillDjGoodsTypeGroupRelations(deepClone({}))
expect(differsWhenNoPrevRaw(cur)).toBe(false)
})
test("substantive cur counts as diff vs missing baseline", () => {
expect(
differsWhenNoPrevRaw(
fillDjGoodsTypeGroupRelations(deepClone(minimalSubstantiveRule))
)
).toBe(true)
})
})
describe("reconciliation same baseline and current (normalized)", () => {
test("identical after normalize and deepEqual", () => {
const baseline = {
groupType: 1,
goodsSource: 1,
expenseCategoryRules: [deepClone(minimalSubstantiveRule.expenseCategoryRules[0])],
goodsTypeGroupRelations: []
}
const cur = { ...deepClone(baseline) }
const prevNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(baseline))
)
const curNorm = normalizeReconciliationRuleForCompare(
fillDjGoodsTypeGroupRelations(deepClone(cur))
)
expect(financialRulePayloadDeepEqual(curNorm, prevNorm)).toBe(true)
})
})
/**
* @jest-environment jsdom
*/
import { shouldIncludeReconciliationTabForProcess } from "@/views/systemConfig/merchant/merchantStep/utils/reconciliationSubmitTabGate"
describe("shouldIncludeReconciliationTabForProcess", () => {
test("无基线槽位:不要求 touched,用于新增可提交/无 prev 对齐场景", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: false,
classificationUserTouched: false,
sessionAdded: false
})
).toBe(true)
})
test("有基线槽位且无 touched/sessionAdded:不进入待校验(挡无操作假脏)", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: false,
sessionAdded: false
})
).toBe(false)
})
test("有基线槽位且 touched:可进入", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: true,
sessionAdded: false
})
).toBe(true)
})
test("有基线槽位且 sessionAdded:可进入", () => {
expect(
shouldIncludeReconciliationTabForProcess({
hasBaselineSlot: true,
classificationUserTouched: false,
sessionAdded: true
})
).toBe(true)
})
})
import { uniquePackageByPackageCode } from "@/views/systemConfig/merchant/merchantStep/utils/groundingUpgradeList"
describe("uniquePackageByPackageCode", () => {
test("dedupes by packageCode preserving first occurrence order", () => {
const input = [
{ packageCode: "a", packageName: "A1" },
{ packageCode: "b", packageName: "B" },
{ packageCode: "a", packageName: "A2" }
]
const out = uniquePackageByPackageCode(input)
expect(out).toHaveLength(2)
expect(out[0].packageName).toBe("A1")
expect(out.map((x) => x.packageCode)).toEqual(["a", "b"])
})
test("treats undefined input as empty", () => {
expect(uniquePackageByPackageCode(undefined)).toEqual([])
})
})
import { schemaSumBy } from "@/views/goods/shelfProduct/utils/calc";
describe("schemaSumBy", () => {
test("有数字, 有字符数字, 有空值时, 返回所有 有效数字的和", () => {
const list = [
{ amount: 10 },
{ amount: "20.5" },
{ amount: undefined },
{ amount: "" },
{ amount: "abc" },
{ amount: null },
];
expect(schemaSumBy(list, "amount")).toBe("30.5元");
});
test("所有都是无效数字时 undefined null '' 'ab' NaN", () => {
const list = [
{ amount: undefined },
{ amount: null },
{ amount: "" },
{ amount: "abc" },
{ amount: NaN },
];
expect(schemaSumBy(list, "amount")).toBe("-");
});
test("所有都是数字时", () => {
const list = [
{ amount: 0 },
{ amount: 0 },
{ amount: 0 },
{ amount: 4 },
];
expect(schemaSumBy(list, "amount")).toBe("4元");
});
test("有数字, 有无效值时", () => {
const list = [
{ amount: 4 },
{ amount: null },
{ amount: undefined },
{ amount: '' },
];
expect(schemaSumBy(list, "amount")).toBe("4元");
});
test("全部都是无效值时", () => {
const list = [
{ amount: NaN },
{ amount: null },
{ amount: undefined },
{ amount: '' },
];
expect(schemaSumBy(list, "amount")).toBe("-");
});
test("既有空值, 又有null, 还有0 的时候", () => {
const list = [
{ fee: null },
{ fee: "" },
{ fee: 0 },
];
expect(schemaSumBy(list, "fee")).toBe("0元");
});
});
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!