import assert from 'node:assert/strict'; import test from 'node:test'; import React from 'react'; import { loadFrontendModule } from './frontend-module.js'; // 原厂价登记汇率设置项的行为测试。不走真实渲染:把 hooks 换成可手动推进的桩,直接调用 // 组件函数拿到元素树,再触发 InputNumber / Button 上的回调——这样才能复现 // 「onChange 与 onPressEnter 在同一次渲染里先后同步触发」这个时序。 const filename = new URL( '../../src/pages/Setting/Ratio/OfficialPriceExchangeRateSetting.jsx', import.meta.url, ); async function mount({ put } = {}) { const hooks = []; let cursor = 0; let effects = []; const calls = { put: [], error: [], success: [], warning: [], refresh: 0 }; const react = { ...React, useState(initial) { const index = cursor++; if (!(index in hooks)) hooks[index] = { value: initial }; const slot = hooks[index]; return [ slot.value, (next) => { slot.value = next; }, ]; }, useRef(initial) { const index = cursor++; if (!(index in hooks)) hooks[index] = { current: initial }; return hooks[index]; }, useEffect(effect, deps) { const index = cursor++; const previous = hooks[index]; if ( !previous || deps.some((dep, i) => !Object.is(dep, previous.deps[i])) ) { hooks[index] = { deps }; effects.push(effect); } }, }; const antd = { Button: 'Button', InputNumber: 'InputNumber', Space: 'Space', Typography: { Text: 'Text' }, }; const Component = ( await loadFrontendModule(filename, { react, antd, 'react-i18next': { useTranslation: () => ({ t: (key) => key }) }, '../../../helpers': { API: { put: (...args) => { calls.put.push(args); return put ? put(...args) : Promise.resolve({ data: { success: true } }); }, }, showError: (message) => calls.error.push(message), showSuccess: (message) => calls.success.push(message), showWarning: (message) => calls.warning.push(message), }, }) ).default; const find = (node, type) => { if (!node || typeof node !== 'object') return null; if (Array.isArray(node)) { for (const child of node) { const hit = find(child, type); if (hit) return hit; } return null; } if (node.type === type) return node; return find(node.props?.children, type); }; let tree; let props; // 渲染一轮并执行这一轮登记的 effect;effect 里若改了 state,需要再 render 一次才会体现 const render = (nextProps = props) => { props = nextProps; cursor = 0; effects = []; tree = Component({ ...props, refresh: () => (calls.refresh += 1) }); effects.forEach((effect) => effect()); return tree; }; return { calls, render, input: () => find(tree, antd.InputNumber), button: () => find(tree, antd.Button), }; } const saved = (value) => ({ options: { OfficialPriceExchangeRate: value } }); const RANGE_ERROR = '请输入大于 0 且不超过 1000 的数字'; test('shows the saved rate once options arrive after mount', async () => { const widget = await mount(); widget.render({ options: {} }); assert.equal(widget.input().props.value, null); widget.render(saved('7')); widget.render(); assert.equal(widget.input().props.value, 7); // 不设 min / max:组件不会把超范围的输入悄悄改成边界值; // 不设 step:小数位跟着 step 走,7 会显示成 7.0 for (const prop of ['min', 'max', 'step']) assert.equal(widget.input().props[prop], undefined, prop); }); test('follows the server value only while the input is untouched', async () => { const widget = await mount(); widget.render(saved('7')); widget.render(); // 没动过输入框:别处改了配置,刷新后跟着变 widget.render(saved('9')); widget.render(); assert.equal(widget.input().props.value, 9); // 正在改:刷新带来的新值不能把输入中的内容冲掉 widget.input().props.onChange(5); widget.render(saved('9.5')); widget.render(); assert.equal(widget.input().props.value, 5); await widget.input().props.onPressEnter(); assert.equal( JSON.stringify(widget.calls.put.map((args) => args[1].value)), JSON.stringify(['5']), ); }); test('Enter saves the value just typed, not the previous render state', async () => { const widget = await mount(); widget.render(saved('7')); widget.render(); // InputNumber 在回车时先同步 onChange 再 onPressEnter,中间没有重新渲染 const input = widget.input(); input.props.onChange(8.5); await input.props.onPressEnter(); // 请求参数是组件所在 VM 域里创建的对象,原型与这里不同,按 JSON 比较 assert.equal( JSON.stringify(widget.calls.put), JSON.stringify([ [ '/api/option/', { key: 'OfficialPriceExchangeRate', value: '8.5' }, { skipErrorHandler: true }, ], ]), ); assert.deepEqual(widget.calls.success, ['保存成功']); assert.equal(widget.calls.refresh, 1); }); test('out-of-range or empty input is rejected instead of saving something else', async () => { for (const typed of [2000, 0, -3, null]) { const widget = await mount(); widget.render(saved('7')); widget.render(); const input = widget.input(); input.props.onChange(typed); await input.props.onPressEnter(); assert.deepEqual(widget.calls.put, [], `输入 ${typed} 不应发请求`); assert.deepEqual(widget.calls.error, [RANGE_ERROR]); } }); test('saving an unchanged rate only warns', async () => { const widget = await mount(); widget.render(saved('7')); widget.render(); await widget.button().props.onClick(); assert.deepEqual(widget.calls.put, []); assert.deepEqual(widget.calls.warning, ['你似乎并没有修改什么']); }); test('a second Enter while the request is pending does not send it twice', async () => { let release; const pending = new Promise((resolve) => { release = resolve; }); const widget = await mount({ put: () => pending }); widget.render(saved('7')); widget.render(); const input = widget.input(); input.props.onChange(8); const first = input.props.onPressEnter(); const second = input.props.onPressEnter(); release({ data: { success: true } }); await Promise.all([first, second]); assert.equal(widget.calls.put.length, 1); // 请求结束后可以再次提交 input.props.onChange(9); await input.props.onPressEnter(); assert.equal(widget.calls.put.length, 2); }); test('a rejected or failed save surfaces the error and unlocks the form', async () => { const rejected = await mount({ put: () => Promise.resolve({ data: { success: false, message: '后端拒绝' } }), }); rejected.render(saved('7')); rejected.render(); rejected.input().props.onChange(8); await rejected.input().props.onPressEnter(); assert.deepEqual(rejected.calls.error, ['后端拒绝']); assert.equal(rejected.calls.refresh, 0); const failed = await mount({ put: () => Promise.reject(new Error('net')) }); failed.render(saved('7')); failed.render(); failed.input().props.onChange(8); await failed.input().props.onPressEnter(); assert.deepEqual(failed.calls.error, ['保存失败,请重试']); await failed.input().props.onPressEnter(); assert.equal(failed.calls.put.length, 2); });