verify-repair-month.cjs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. const assert = require('node:assert/strict');
  3. const fs = require('node:fs');
  4. const path = require('node:path');
  5. const vm = require('node:vm');
  6. /**
  7. * @param {string} source - 页面源码
  8. * @param {string} name - 函数名
  9. * @returns {string} 可独立执行的函数源码
  10. */
  11. function extractFunction(source, name) {
  12. const pattern = new RegExp('function ' + name + '\\(');
  13. const match = pattern.exec(source);
  14. assert.ok(match, '缺少方法 ' + name);
  15. const end = source.indexOf('\n/**', match.index + match[0].length);
  16. return source.slice(match.index, end < 0 ? source.length : end);
  17. }
  18. const sourcePath = path.resolve(__dirname, '../src/timecard-repair.oyd.jsx');
  19. const source = fs.readFileSync(sourcePath, 'utf8');
  20. const methods = vm.runInNewContext(
  21. ['toTwoDigitText', 'resolveRepairMonth']
  22. .map((name) => extractFunction(source, name)).join('\n')
  23. + '\n({resolveRepairMonth})',
  24. );
  25. assert.deepEqual(
  26. { ...methods.resolveRepairMonth('', new Date(2026, 9, 21)) },
  27. { year: 2026, month: 9 },
  28. '未传月份时应默认上一个月',
  29. );
  30. assert.deepEqual(
  31. { ...methods.resolveRepairMonth('202610', new Date(2026, 9, 21)) },
  32. { year: 2026, month: 9 },
  33. '传入当前月时应回退到上一个月',
  34. );
  35. assert.deepEqual(
  36. { ...methods.resolveRepairMonth('202608', new Date(2026, 9, 21)) },
  37. { year: 2026, month: 8 },
  38. '显式历史月份应保持不变',
  39. );
  40. assert.deepEqual(
  41. { ...methods.resolveRepairMonth('202701', new Date(2027, 0, 10)) },
  42. { year: 2026, month: 12 },
  43. '一月份回退时应正确跨年',
  44. );
  45. console.log('PASS 补填页面默认月份解析');