Commit abfbbfac authored by zengqiang's avatar zengqiang

feat: 新增H5提现确认收款页和单元测试

parent 5a6324b0
......@@ -24,3 +24,16 @@ npm run lint
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
### 变更记录
本次更新主要围绕微信商家转账升级,主要变更包括:
- 新增确认收款中间页
- 新增处理中状态展示
- 新增提现状态枚举展示
### 页面说明
**提现相关页面:**
- **确认收款页**: 用户发起提现后,需在此页确认收款。通过 JSBridge 调用原生能力调起微信确认。
- **提现记录列表**: 展示提现记录,支持新的提现状态枚举(处理中、待确认收款、已成功、失败)。
......@@ -6,6 +6,7 @@ module.exports = {
'@babel/plugin-proposal-logical-assignment-operators',
'@babel/plugin-proposal-optional-chaining'
]
}]
}],
'@babel/preset-typescript'
]
}
module.exports = {
testEnvironment: 'jsdom',
moduleFileExtensions: [
'js',
'ts',
'json',
'vue',
],
transform: {
'^.+\.ts$': 'ts-jest',
'^.+\.js$': 'babel-jest',
'.*\.(vue)$' : '@vue/vue3-jest',
},
testMatch: [
'**/__tests__/**/*.spec.[jt]s?(x)',
'**/__tests__/**/*.test.[jt]s?(x)',
'**/src/**/*.spec.[jt]s?(x)',
'**/src/**/*.test.[jt]s?(x)',
],
moduleNameMapper: {
'^@/(.*)$' : '<rootDir>/src/$1'
},
};
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -6,7 +6,9 @@
"build": "vue-cli-service build",
"serve": "vue-cli-service serve",
"dev": "vue-cli-service serve",
"lint": "vue-cli-service lint --fix"
"lint": "vue-cli-service lint --fix",
"test": "vue-cli-service test:unit",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"amfe-flexible": "^2.2.1",
......@@ -20,6 +22,7 @@
"vuex": "^4.0.2"
},
"devDependencies": {
"@babel/preset-typescript": "^7.28.5",
"@geek/webpack-upload-assets-plugin": "^1.0.1",
"@types/js-cookie": "^3.0.3",
"@typescript-eslint/eslint-plugin": "^5.4.0",
......@@ -28,11 +31,14 @@
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-plugin-router": "~5.0.0",
"@vue/cli-plugin-typescript": "~5.0.0",
"@vue/cli-plugin-unit-jest": "^5.0.9",
"@vue/cli-plugin-vuex": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"@vue/eslint-config-standard": "^6.1.0",
"@vue/eslint-config-typescript": "^9.1.0",
"@vue/preload-webpack-plugin": "^2.0.0",
"@vue/test-utils": "^2.4.0-alpha.2",
"@vue/vue3-jest": "^27.0.0",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0",
......@@ -44,6 +50,7 @@
"sass": "^1.32.7",
"sass-loader": "^12.0.0",
"ts-import-plugin": "^1.6.7",
"ts-jest": "^27.1.5",
"typescript": "~4.5.5",
"webpack-merge": "^5.7.3"
}
......
......@@ -25,6 +25,16 @@ const routes: Array<RouteRecordRaw> = [
path: '/test/paging',
name: 'test-paging',
component: () => import('../views/test/paging.vue')
},
{
path: '/withdraw/confirm-receipt',
name: 'WithdrawConfirmReceipt',
component: () => import('../views/withdraw/ConfirmReceipt.vue'),
},
{
path: '/withdraw/processing-status',
name: 'WithdrawProcessingStatus',
component: () => import('../views/withdraw/ProcessingStatus.vue'),
}
]
......
import { invokeNativeMethod } from '@/util/use-native-bridge';
interface NativeMerchantTransferResponse {
errMsg: string; // e.g., 'requestMerchantTransfer:ok' or an error message
// Add other fields if the native method returns more data
}
/**
* Calls the native JSBridge to request merchant transfer (similar to wx.requestMerchantTransfer).
* @param {string} packageInfo - The package information received from the backend for native transfer.
* @returns {Promise<NativeMerchantTransferResponse>}
*/
export function requestNativeMerchantTransfer(packageInfo: string): Promise<NativeMerchantTransferResponse> {
return invokeNativeMethod<NativeMerchantTransferResponse, string>({
type: 'requestMerchantTransfer', // Assuming the native app exposes this method type
data: packageInfo,
});
}
import { post, get } from '../request';
interface WithdrawRequestData {
amount: string;
accountInfo: {
name: string;
bank: string;
type: string;
};
// Add other necessary fields as per backend API
}
interface WithdrawResponseData {
code: number;
message?: string;
data?: {
orderId: string;
packageInfo?: string; // For WeChat Pay H5 or other payment bridge data
};
}
interface WithdrawStatusResponseData {
code: number;
message?: string;
data?: {
state: string; // e.g., PROCESSING, SUCCESS, FAILED
// Add other status details
};
}
/**
* 发起提现申请
* @param {WithdrawRequestData} data - 提现请求数据
* @returns {Promise<WithdrawResponseData>}
*/
export function postWithdraw(data: WithdrawRequestData): Promise<WithdrawResponseData> {
return post(
'/api-jksxb-h5/withdraw',
data,
);
}
/**
* 查询转账状态
* @param {string} orderId - 订单ID
* @returns {Promise<WithdrawStatusResponseData>}
*/
export function queryWithdrawStatus(orderId: string): Promise<WithdrawStatusResponseData> {
return get(
`/api-jksxb-h5/withdraw/status?orderId=${orderId}`,
);
}
......@@ -114,6 +114,8 @@ function invokeNativeMethod<T = any, P = any> (arg: { type: string; data?: P }):
})
}
export { invokeNativeMethod }
/**
* 微信登录
*/
......
import { mount, flushPromises } from '@vue/test-utils';
import { defineComponent } from 'vue';
import WithdrawList from '../withdraw-list.vue';
import { getWithdrawList } from '@/server/api/bonus';
import { WithdrawStatus } from '@/model/bonus/constant';
import { createStore } from 'vuex';
// Mock PullRefreshList component
const PullRefreshListStub = defineComponent({
template: `
<div class="pull-refresh-list-stub">
<slot :list="mockedList"></slot>
</div>
`,
props: {
request: { type: Function, required: true },
paramsFn: { type: Function, required: true },
},
data() {
return {
mockedList: [] as any[],
};
},
watch: {
request: {
immediate: true,
async handler(this: any, newVal: Function) {
if (newVal) {
try {
const res = await newVal(this.paramsFn());
this.mockedList = res.data.list;
} catch (error) {
console.error('Error fetching withdraw list:', error);
}
}
},
},
},
});
// Mock API
jest.mock('@/server/api/bonus', () => ({
getWithdrawList: jest.fn(),
}));
describe('WithdrawList.vue', () => {
let store: ReturnType<typeof createStore>;
beforeEach(() => {
jest.clearAllMocks();
store = createStore({
state: {
bonus: {
studentId: 'testStudent123',
},
},
});
});
it('renders an empty list initially', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: { list: [], total: 0 },
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
expect(wrapper.findAll('.withdraw-list')).toHaveLength(0);
expect(getWithdrawList).toHaveBeenCalledWith({ studentId: 'testStudent123' });
});
it('renders a list with "提现中" (WITHDRAWING) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 1,
status: WithdrawStatus.WITHDRAWING,
accountName: '张三',
withdrawAmount: 100.00,
withdrawApplyTime: '2024-01-01 10:00:00',
expectedPayTime: '2024-01-02 10:00:00',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现中');
expect(withdrawItem.find('.header-status label').text()).toBe('请耐心等候~');
expect(withdrawItem.find('.apply-money').text()).toBe('¥100.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-shijian');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:张三');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 10:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('预计时间:2024-01-02 10:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').exists()).toBe(false); // No 到账时间
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(5)').exists()).toBe(false); // No 失败时间
});
it('renders a list with "提现成功" (RECEIVED) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 2,
status: WithdrawStatus.RECEIVED,
accountName: '李四',
withdrawAmount: 50.00,
withdrawApplyTime: '2024-01-01 09:00:00',
withdrawPayTime: '2024-01-01 11:00:00',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现成功');
expect(withdrawItem.find('.header-status label').exists()).toBe(false); // No 请耐心等候
expect(withdrawItem.find('.apply-money').text()).toBe('-¥50.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-jindutiaoqiandai');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:李四');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 09:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('到账时间:2024-01-01 11:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').exists()).toBe(false); // No 失败时间
});
it('renders a list with "提现失败" (FAILED) status', async () => {
(getWithdrawList as jest.Mock).mockResolvedValue({
code: 0,
data: {
list: [
{
id: 3,
status: WithdrawStatus.FAILED,
accountName: '王五',
withdrawAmount: 200.00,
withdrawApplyTime: '2024-01-01 08:00:00',
failTime: '2024-01-01 08:30:00',
reason: '银行卡信息有误',
},
],
total: 1,
},
});
const wrapper = mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
const withdrawItem = wrapper.find('.withdraw-list');
expect(withdrawItem.exists()).toBe(true);
expect(withdrawItem.find('.header-status span').text()).toBe('提现失败');
expect(withdrawItem.find('.header-status label').exists()).toBe(false); // No 请耐心等候
expect(withdrawItem.find('.apply-money').text()).toBe('¥200.00');
expect(withdrawItem.find('.iconfont').classes()).toContain('icon-xiazaishibai');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(1)').text()).toBe('微信提现:王五');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(2)').text()).toBe('申请时间:2024-01-01 08:00:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(3)').text()).toBe('失败时间:2024-01-01 08:30:00');
expect(withdrawItem.find('.withdraw-list-detail li:nth-child(4)').text()).toBe('失败原因:银行卡信息有误');
});
it('handles API error gracefully', async () => {
(getWithdrawList as jest.Mock).mockRejectedValue(new Error('API error'));
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
mount(WithdrawList, {
global: {
plugins: [store],
stubs: { 'pull-refresh-list': PullRefreshListStub },
},
});
await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith('Error fetching withdraw list:', expect.any(Error));
consoleErrorSpy.mockRestore();
});
});
<template>
<div class="container">
<div class="info-card">
<span class="label">提现金额</span>
<span class="value amount">¥ {{ amount }}</span>
</div>
<div class="info-card">
<div class="info-item">
<span class="label">收款账户</span>
<span class="value">{{ accountInfo.name }} ({{ accountInfo.bank }})</span>
</div>
<div class="info-item">
<span class="label">账户类型</span>
<span class="value">{{ accountInfo.type }}</span>
</div>
</div>
<button class="confirm-button" @click="handleConfirm">确认提现</button>
<div class="footer-tip">
点击确认即表示您同意XXXX协议
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { postWithdraw } from '@/server/api/withdrawService';
import { requestNativeMerchantTransfer } from '@/server/api/withdrawNativeService';
export default defineComponent({
name: 'ConfirmReceipt',
data() {
return {
amount: '0.00',
accountInfo: {
name: '',
bank: '',
type: '',
},
};
},
created() {
// In H5, parameters would typically come from route query or state management
const query = this.$route.query;
this.amount = (query.amount as string) || '0.00';
try {
this.accountInfo = JSON.parse(decodeURIComponent((query.accountInfo as string) || '{}'));
} catch (e) {
console.error('Failed to parse accountInfo', e);
this.accountInfo = { name: '', bank: '', type: '' };
}
// H5 specific compatibility check or logic can go here if needed
// For now, we assume canUseMerchantTransfer is true for H5 context unless specific platform bridges are identified.
},
methods: {
async handleConfirm() {
try {
// const withdrawRes = await postWithdraw({
// amount: this.amount,
// accountInfo: this.accountInfo,
// });
// Placeholder for H5 specific payment logic
// This is where the "三端确认收款适配" (three-end confirm receipt adaptation) logic would reside.
// For H5 embedded in App, this might involve calling a JSBridge.
// For Official Account H5, this might involve redirecting to WeChat Pay H5.
// Since specifics are not provided, this will be a generic placeholder.
const withdrawRes = await postWithdraw({
amount: this.amount,
accountInfo: this.accountInfo,
});
if (withdrawRes.code === 0 && withdrawRes.data) {
const { orderId, packageInfo } = withdrawRes.data;
if (packageInfo) {
console.log('Processing packageInfo for H5 payment via JSBridge...', packageInfo);
try {
const nativeTransferRes = await requestNativeMerchantTransfer(packageInfo);
if (nativeTransferRes.errMsg === 'requestMerchantTransfer:ok') {
this.$router.replace({
path: '/withdraw/processing-status',
query: { status: 'WAIT_USER_CONFIRM', orderId: orderId },
});
} else {
alert(nativeTransferRes.errMsg || '用户取消或提现失败');
}
} catch (nativeError) {
console.error('Native transfer request error:', nativeError);
alert((nativeError as Error).message || 'Native transfer failed, please retry.');
}
} else {
// Direct to processing status if no further payment step needed
this.$router.replace({
path: '/withdraw/processing-status',
query: { status: 'PROCESSING', orderId: orderId },
});
}
} else {
// Handle backend API error
// this.$toast.fail(withdrawRes.message || '提现请求失败');
alert(withdrawRes.message || '提现请求失败'); // Generic alert
}
} catch (error) {
console.error('Withdrawal request error:', error);
// this.$toast.fail(error.message || '网络请求失败,请稍后重试');
alert(error.message || '网络请求失败,请稍后重试'); // Generic alert
} finally {
// Hide loading indicator
// this.$toast.clear();
}
},
},
});
</script>
<style scoped>
.container {
padding: 4vw; /* 30rpx = 4vw (30 * 0.1333) */
background-color: #f8f8f8;
min-height: 100vh;
box-sizing: border-box;
}
.info-card {
background-color: #ffffff;
border-radius: 2.133vw; /* 16rpx */
padding: 4vw; /* 30rpx */
margin-bottom: 2.666vw; /* 20rpx */
box-shadow: 0 0.266vw 1.333vw rgba(0, 0, 0, 0.05); /* 0 2rpx 10rpx */
}
.info-card .label {
font-size: 3.733vw; /* 28rpx */
color: #888888;
margin-right: 2.666vw; /* 20rpx */
}
.info-card .value {
font-size: 3.733vw; /* 28rpx */
color: #333333;
}
.info-card .amount {
font-size: 6.4vw; /* 48rpx */
font-weight: bold;
color: #333333;
display: block;
text-align: center;
margin-top: 2.666vw; /* 20rpx */
}
.info-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.333vw 0; /* 10rpx */
}
.info-item + .info-item {
border-top: 0.133vw solid #eee; /* 1rpx */
margin-top: 1.333vw; /* 10rpx */
padding-top: 2.666vw; /* 20rpx */
}
.confirm-button {
width: 100%;
height: 12vw; /* 90rpx */
line-height: 12vw; /* 90rpx */
background-color: #07c160;
color: #ffffff;
font-size: 4.533vw; /* 34rpx */
border-radius: 6vw; /* 45rpx */
margin-top: 5.333vw; /* 40rpx */
border: none; /* Add border none for button */
}
.footer-tip {
text-align: center;
font-size: 3.2vw; /* 24rpx */
color: #aaaaaa;
margin-top: 4vw; /* 30rpx */
}
</style>
\ No newline at end of file
<template>
<div class="container">
<img class="status-icon" :src="icon" mode="aspectFit" alt="Status Icon" />
<p class="status-text" :class="statusClass">{{ statusText }}</p>
<div class="detail-card" v-if="orderId">
<div class="detail-item">
<span class="label">订单号</span>
<span class="value">{{ orderId }}</span>
</div>
<div class="detail-item">
<span class="label">当前状态</span>
<span class="value">{{ status }}</span>
</div>
</div>
<button v-if="statusMap[status] && statusMap[status].action" class="action-button" @click="handleAction">
{{ statusMap[status].action === 'confirm' ? '去确认收款' : '重新提现' }}
</button>
<div class="footer-tip">
如有疑问,请联系客服
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { queryWithdrawStatus } from '@/server/api/withdrawService';
interface StatusConfig {
text: string;
icon: string;
action?: 'confirm' | 'retry';
}
interface StatusMap {
[key: string]: StatusConfig;
}
export default defineComponent({
name: 'ProcessingStatus',
data() {
return {
status: 'PROCESSING', // PROCESSING, SUCCESS, FAIL, etc.
statusText: '提现处理中...',
icon: '/assets/images/processing.png', // Placeholder for actual image path
orderId: '',
pollingInterval: null as ReturnType<typeof setInterval> | null,
pollingCount: 0,
maxPollingAttempts: 10,
statusMap: {
'ACCEPTED': { text: '提现处理中...', icon: '/assets/images/processing.png' },
'PROCESSING': { text: '提现处理中...', icon: '/assets/images/processing.png' },
'WAIT_USER_CONFIRM': { text: '提现处理中,待用户确认收款', icon: '/assets/images/processing.png', action: 'confirm' },
'TRANSFERING': { text: '转账处理中...', icon: '/assets/images/processing.png' },
'SUCCESS': { text: '提现成功', icon: '/assets/images/success.png' },
'FAILED': { text: '提现失败', icon: '/assets/images/fail.png', action: 'retry' },
'CANCELING': { text: '转账撤销中...', icon: '/assets/images/processing.png' },
'CANCELLED': { text: '转账已撤销', icon: '/assets/images/fail.png', action: 'retry' },
'UNKNOWN': { text: '状态未知,请稍后查询', icon: '/assets/images/processing.png' },
} as StatusMap,
};
},
created() {
const query = this.$route.query;
this.orderId = (query.orderId as string) || '';
this.status = (query.status as string) || 'PROCESSING';
this.updateStatusDisplay(this.status);
},
mounted() {
this.startPolling();
},
beforeUnmount() {
this.stopPolling();
},
methods: {
updateStatusDisplay(statusCode: string) {
const displayStatus = this.statusMap[statusCode] || this.statusMap['UNKNOWN'];
this.statusText = displayStatus.text;
// Assuming image assets are in `/public/assets/images/` or handled by webpack aliasing
// For now, use relative path or direct path if assets are served from root
this.icon = displayStatus.icon.replace('/assets/images/', '/img/'); // Adjust path based on H5 asset structure
},
startPolling() {
this.stopPolling(); // Ensure no duplicate intervals
this.pollingInterval = setInterval(async () => {
this.pollingCount++;
if (this.pollingCount > this.maxPollingAttempts) {
this.stopPolling();
console.warn('Max polling attempts reached. Stopping polling.');
this.updateStatusDisplay('UNKNOWN');
return;
}
await this.queryTransferStatus();
}, 5000); // Poll every 5 seconds
},
stopPolling() {
if (this.pollingInterval) {
clearInterval(this.pollingInterval);
this.pollingInterval = null;
}
},
async queryTransferStatus() {
if (!this.orderId) {
console.error('No orderId available for status query.');
this.stopPolling();
return;
}
console.log(`Polling status for orderId: ${this.orderId}, attempt: ${this.pollingCount}`);
try {
// const res = await queryWithdrawStatus(this.orderId);
const res = await queryWithdrawStatus(this.orderId);
if (res.code === 0 && res.data && res.data.state) {
const newStatus = res.data.state;
this.status = newStatus;
this.updateStatusDisplay(newStatus);
if (['SUCCESS', 'FAILED', 'CANCELLED'].includes(newStatus)) {
this.stopPolling();
}
} else {
console.error('Failed to query transfer status:', res.message || 'Unknown error');
}
} catch (error) {
console.error('Error querying transfer status:', error);
}
},
handleAction() {
const currentAction = this.statusMap[this.status]?.action;
if (currentAction === 'confirm') {
// Navigate back to confirm page
this.$router.replace({ path: '/withdraw/confirm-receipt', query: { ...this.$route.query } });
} else if (currentAction === 'retry') {
// Navigate to withdrawal initiation page (placeholder)
this.$router.replace({ path: '/withdraw/initiate-withdrawal' });
}
},
},
computed: {
statusClass(): string {
const currentStatus = this.status.toLowerCase();
if (['accepted', 'processing', 'transfering', 'unknown'].includes(currentStatus)) {
return 'status-processing';
} else if (currentStatus === 'wait_user_confirm') {
return 'status-wait-confirm';
} else if (currentStatus === 'success') {
return 'status-success';
} else if (['failed', 'cancelled'].includes(currentStatus)) {
return 'status-failed';
}
return '';
},
},
});
</script>
<style scoped>
.container {
display: flex;
flex-direction: column;
align-items: center;
padding: 8vw 4vw; /* 60rpx 30rpx */
background-color: #f8f8f8;
min-height: 100vh;
box-sizing: border-box;
}
.status-icon {
width: 21.333vw; /* 160rpx */
height: 21.333vw; /* 160rpx */
margin-bottom: 5.333vw; /* 40rpx */
}
.status-text {
font-size: 5.066vw; /* 38rpx */
font-weight: bold;
color: #333333;
margin-bottom: 8vw; /* 60rpx */
text-align: center;
}
.status-text.status-processing {
color: #1989fa; /* Blue for processing */
}
.status-text.status-wait-confirm {
color: #ff976a; /* Orange for waiting confirmation */
}
.status-text.status-success {
color: #07c160; /* Green for success */
}
.status-text.status-failed {
color: #ee0a24; /* Red for failed/cancelled */
}
.detail-card {
background-color: #ffffff;
border-radius: 2.133vw; /* 16rpx */
padding: 4vw; /* 30rpx */
width: 100%;
max-width: 80vw; /* Approx 600rpx */
box-shadow: 0 0.266vw 1.333vw rgba(0, 0, 0, 0.05); /* 0 2rpx 10rpx */
margin-bottom: 8vw; /* 60rpx */
}
.detail-item {
display: flex;
justify-content: space-between;
padding: 1.333vw 0; /* 10rpx */
font-size: 3.733vw; /* 28rpx */
color: #555555;
}
.detail-item + .detail-item {
border-top: 0.133vw solid #eee; /* 1rpx */
margin-top: 1.333vw; /* 10rpx */
padding-top: 2.666vw; /* 20rpx */
}
.detail-item .label {
color: #888888;
}
.action-button {
width: 100%;
max-width: 80vw; /* Approx 600rpx */
height: 12vw; /* 90rpx */
line-height: 12vw; /* 90rpx */
background-color: #07c160;
color: #ffffff;
font-size: 4.533vw; /* 34rpx */
border-radius: 6vw; /* 45rpx */
margin-top: 5.333vw; /* 40rpx */
border: none; /* Add border none for button */
}
.footer-tip {
text-align: center;
font-size: 3.2vw; /* 24rpx */
color: #aaaaaa;
margin-top: 8vw; /* 60rpx */
}
</style>
\ No newline at end of file
import { mount, flushPromises } from '@vue/test-utils';
import ConfirmReceipt from '../ConfirmReceipt.vue';
import { postWithdraw } from '@/server/api/withdrawService';
import { requestNativeMerchantTransfer } from '@/server/api/withdrawNativeService';
// Mock vue-router
const mockRouter = {
replace: jest.fn(),
};
const mockRoute = {
query: {
amount: '100.00',
accountInfo: encodeURIComponent(JSON.stringify({ name: 'Test User', bank: 'Test Bank', type: 'Debit' })),
},
};
jest.mock('@/server/api/withdrawService');
jest.mock('@/server/api/withdrawNativeService');
describe('ConfirmReceipt.vue', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('renders correctly with initial data from route query', () => {
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
expect(wrapper.find('.amount').text()).toBe('¥ 100.00');
expect(wrapper.findAll('.info-item .value')[0].text()).toBe('Test User (Test Bank)');
expect(wrapper.findAll('.info-item .value')[1].text()).toBe('Debit');
});
it('calls postWithdraw and redirects to processing status on success without packageInfo', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER123', packageInfo: null },
});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(postWithdraw).toHaveBeenCalledWith({
amount: '100.00',
accountInfo: { name: 'Test User', bank: 'Test Bank', type: 'Debit' },
});
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/processing-status',
query: { status: 'PROCESSING', orderId: 'ORDER123' },
});
});
it('calls postWithdraw, then requestNativeMerchantTransfer, and redirects to processing status with WAIT_USER_CONFIRM if packageInfo is present and native call succeeds', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER456', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockResolvedValueOnce({
errMsg: 'requestMerchantTransfer:ok',
});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(postWithdraw).toHaveBeenCalledWith({
amount: '100.00',
accountInfo: { name: 'Test User', bank: 'Test Bank', type: 'Debit' },
});
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledWith('some_package_info_string');
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/processing-status',
query: { status: 'WAIT_USER_CONFIRM', orderId: 'ORDER456' },
});
});
it('handles native transfer error when packageInfo is present', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER789', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockRejectedValueOnce(new Error('Native transfer error'));
const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(alertSpy).toHaveBeenCalledWith('Native transfer error');
expect(mockRouter.replace).not.toHaveBeenCalled();
alertSpy.mockRestore();
});
it('handles native transfer cancellation/failure when packageInfo is present', async () => {
(postWithdraw as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { orderId: 'ORDER901', packageInfo: 'some_package_info_string' },
});
(requestNativeMerchantTransfer as jest.Mock).mockResolvedValueOnce({
errMsg: 'requestMerchantTransfer:fail user cancel',
});
const alertSpy = jest.spyOn(window, 'alert').mockImplementation(() => {});
const wrapper = mount(ConfirmReceipt, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.find('.confirm-button').trigger('click');
await flushPromises();
expect(postWithdraw).toHaveBeenCalledTimes(1);
expect(requestNativeMerchantTransfer).toHaveBeenCalledTimes(1);
expect(alertSpy).toHaveBeenCalledWith('requestMerchantTransfer:fail user cancel');
expect(mockRouter.replace).not.toHaveBeenCalled();
alertSpy.mockRestore();
});
});
import { mount, flushPromises } from '@vue/test-utils';
import ProcessingStatus from '../ProcessingStatus.vue';
import { queryWithdrawStatus } from '@/server/api/withdrawService';
// Mock vue-router
const mockRouter = {
replace: jest.fn(),
};
const mockRoute = {
query: {
orderId: 'ORDER789',
status: 'PROCESSING',
},
};
jest.mock('@/server/api/withdrawService');
describe('ProcessingStatus.vue', () => {
let setIntervalSpy: jest.SpyInstance;
let clearIntervalSpy: jest.SpyInstance;
beforeEach(() => {
jest.clearAllMocks();
setIntervalSpy = jest.spyOn(window, 'setInterval').mockReturnValue(123 as any); // Mock interval ID
clearIntervalSpy = jest.spyOn(window, 'clearInterval');
});
afterEach(() => {
setIntervalSpy.mockRestore();
clearIntervalSpy.mockRestore();
});
it('renders correctly with initial data and starts polling', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').text()).toBe('提现处理中...');
expect(wrapper.find('.detail-item .value').text()).toBe('ORDER789');
expect(setIntervalSpy).toHaveBeenCalledTimes(1);
expect(clearIntervalSpy).toHaveBeenCalledTimes(0); // No clearInterval on initial mount as pollingInterval is null
});
it('stops polling on unmount', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
wrapper.unmount();
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One from unmount
expect(clearIntervalSpy).toHaveBeenCalledWith(123);
});
it('updates status display based on API response and stops polling on success', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { state: 'SUCCESS' },
});
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
// Manually trigger polling interval logic
// The setInterval is mocked, so we need to manually call the handler
await (wrapper.vm as any).queryTransferStatus();
await flushPromises();
expect(wrapper.find('.status-text').text()).toBe('提现成功');
expect(wrapper.vm.status).toBe('SUCCESS');
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One after success
});
it('updates status display based on API response and stops polling on failed', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 0,
data: { state: 'FAILED' },
});
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
await (wrapper.vm as any).queryTransferStatus();
await flushPromises();
expect(wrapper.find('.status-text').text()).toBe('提现失败');
expect(wrapper.vm.status).toBe('FAILED');
expect(clearIntervalSpy).toHaveBeenCalledTimes(1); // One after failed
});
it('applies "status-processing" class for PROCESSING status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'PROCESSING' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-processing');
});
it('applies "status-wait-confirm" class for WAIT_USER_CONFIRM status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-wait-confirm');
});
it('applies "status-success" class for SUCCESS status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'SUCCESS' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-success');
});
it('applies "status-failed" class for FAILED status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'FAILED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-failed');
});
it('applies "status-failed" class for CANCELLED status', () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'CANCELLED' } },
$router: mockRouter,
},
},
});
expect(wrapper.find('.status-text').classes()).toContain('status-failed');
});
it('redirects to confirm-receipt on handleAction when status is WAIT_USER_CONFIRM', async () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' } },
$router: mockRouter,
},
},
});
await wrapper.vm.$nextTick(); // Wait for data to be set up
wrapper.find('.action-button').trigger('click');
await flushPromises();
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/confirm-receipt',
query: { orderId: 'ORDER789', status: 'WAIT_USER_CONFIRM' },
});
});
it('redirects to initiate-withdrawal on handleAction when status is FAILED (retry)', async () => {
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: { query: { orderId: 'ORDER789', status: 'FAILED' } },
$router: mockRouter,
},
},
});
await wrapper.vm.$nextTick(); // Wait for data to be set up
wrapper.find('.action-button').trigger('click');
await flushPromises();
expect(mockRouter.replace).toHaveBeenCalledTimes(1);
expect(mockRouter.replace).toHaveBeenCalledWith({
path: '/withdraw/initiate-withdrawal',
});
});
it('handles API error during polling', async () => {
(queryWithdrawStatus as jest.Mock).mockRejectedValueOnce(new Error('Network error during polling'));
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
await (wrapper.vm as any).queryTransferStatus();
await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith('Error querying transfer status:', expect.any(Error));
expect(wrapper.vm.status).toBe('PROCESSING'); // Status should remain unchanged or go to UNKNOWN after max attempts
// Polling continues until max attempts or terminal state is reached
consoleErrorSpy.mockRestore();
});
it('handles non-successful API response during polling', async () => {
(queryWithdrawStatus as jest.Mock).mockResolvedValueOnce({
code: 1, // Non-zero code
message: 'Transfer status query failed',
data: null,
});
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
const wrapper = mount(ProcessingStatus, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter,
},
},
});
await (wrapper.vm as any).queryTransferStatus();
await flushPromises();
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Failed to query transfer status:', 'Transfer status query failed'
);
expect(wrapper.vm.status).toBe('PROCESSING'); // Status should remain unchanged
consoleErrorSpy.mockRestore();
});
});
......@@ -13,7 +13,8 @@
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
"webpack-env",
"jest"
],
"paths": {
"@/*": [
......
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment