Files
nxxmdata/backend/test-coordinate-input-flow.js

229 lines
6.2 KiB
JavaScript
Raw Normal View History

2025-08-27 15:36:36 +08:00
const { Farm } = require('./models');
const { sequelize } = require('./config/database');
const farmController = require('./controllers/farmController');
// 模拟Express请求和响应对象
function createMockReq(body, params = {}) {
return {
body,
params
};
}
function createMockRes() {
const res = {
statusCode: 200,
data: null,
status: function(code) {
this.statusCode = code;
return this;
},
json: function(data) {
this.data = data;
return this;
}
};
return res;
}
// 模拟前端输入处理逻辑
function simulateFrontendInputProcessing(userInput) {
console.log(`\n🔍 模拟用户输入: "${userInput}"`);
// 模拟 a-input-number 的 parser 函数
const parser = (value) => {
if (!value) return value;
// 移除非数字字符,保留小数点和负号
const cleaned = value.toString().replace(/[^\d.-]/g, '');
// 确保只有一个小数点和负号在开头
const parts = cleaned.split('.');
if (parts.length > 2) {
return parts[0] + '.' + parts.slice(1).join('');
}
return cleaned;
};
const parsedValue = parser(userInput);
console.log(` 📝 Parser处理后: "${parsedValue}"`);
// 模拟 v-model 的数值转换
let finalValue;
if (parsedValue === '' || parsedValue === undefined || parsedValue === null) {
finalValue = undefined;
} else {
const numValue = parseFloat(parsedValue);
finalValue = isNaN(numValue) ? undefined : numValue;
}
console.log(` 🔢 最终绑定值: ${finalValue} (类型: ${typeof finalValue})`);
return finalValue;
}
// 测试各种用户输入场景
async function testCoordinateInputFlow() {
console.log('=== 经纬度输入流程测试 ===\n');
let testFarmId = null;
try {
// 1. 创建测试记录
console.log('1. 创建测试养殖场...');
const createReq = createMockReq({
name: '输入测试农场',
owner: '测试负责人',
phone: '13800138003',
address: '测试地址',
longitude: 106.2309,
latitude: 38.4872,
status: 'active'
});
const createRes = createMockRes();
await farmController.createFarm(createReq, createRes);
testFarmId = createRes.data.data.id;
console.log('✓ 创建成功初始location:', createRes.data.data.location);
// 2. 测试各种用户输入场景
const testCases = [
{
name: '正常小数输入',
longitude: '106.2400',
latitude: '38.4900'
},
{
name: '整数输入',
longitude: '106',
latitude: '38'
},
{
name: '高精度小数输入',
longitude: '106.234567',
latitude: '38.487654'
},
{
name: '负数输入',
longitude: '-106.2400',
latitude: '-38.4900'
},
{
name: '包含非法字符的输入',
longitude: '106.24abc',
latitude: '38.49xyz'
},
{
name: '多个小数点的输入',
longitude: '106.24.56',
latitude: '38.49.78'
},
{
name: '空字符串输入',
longitude: '',
latitude: ''
},
{
name: '只输入小数点',
longitude: '.',
latitude: '.'
},
{
name: '边界值输入',
longitude: '180.0',
latitude: '90.0'
},
{
name: '超出范围的输入',
longitude: '200.0',
latitude: '100.0'
}
];
for (let i = 0; i < testCases.length; i++) {
const testCase = testCases[i];
console.log(`\n${i + 2}. 测试场景: ${testCase.name}`);
// 模拟前端输入处理
const processedLongitude = simulateFrontendInputProcessing(testCase.longitude);
const processedLatitude = simulateFrontendInputProcessing(testCase.latitude);
// 构建提交数据
const submitData = {
name: '输入测试农场',
owner: '测试负责人',
phone: '13800138003',
address: '测试地址',
longitude: processedLongitude,
latitude: processedLatitude,
status: 'active'
};
console.log(` 📤 提交数据:`, {
longitude: submitData.longitude,
latitude: submitData.latitude
});
// 调用后端API
const updateReq = createMockReq(submitData, { id: testFarmId });
const updateRes = createMockRes();
try {
await farmController.updateFarm(updateReq, updateRes);
console.log(` ✅ 更新成功:`, {
location: updateRes.data.data.location,
has_lng: 'lng' in (updateRes.data.data.location || {}),
has_lat: 'lat' in (updateRes.data.data.location || {})
});
// 验证数据范围
const location = updateRes.data.data.location || {};
if (location.lng !== undefined) {
if (location.lng < -180 || location.lng > 180) {
console.log(` ⚠️ 警告: 经度超出有效范围 (-180~180): ${location.lng}`);
}
}
if (location.lat !== undefined) {
if (location.lat < -90 || location.lat > 90) {
console.log(` ⚠️ 警告: 纬度超出有效范围 (-90~90): ${location.lat}`);
}
}
} catch (error) {
console.log(` ❌ 更新失败:`, error.message);
}
}
console.log('\n=== 输入流程测试完成 ===');
} catch (error) {
console.error('❌ 测试过程中出现错误:', error);
throw error;
} finally {
// 清理测试数据
if (testFarmId) {
console.log('\n🧹 清理测试数据...');
try {
await Farm.destroy({ where: { id: testFarmId } });
console.log('✓ 测试数据已清理');
} catch (error) {
console.error('清理测试数据失败:', error);
}
}
}
}
// 运行测试
if (require.main === module) {
testCoordinateInputFlow()
.then(() => {
console.log('\n🎉 所有输入流程测试完成!');
process.exit(0);
})
.catch((error) => {
console.error('\n💥 输入流程测试失败:', error.message);
process.exit(1);
});
}
module.exports = { testCoordinateInputFlow };