dictSnapshot.test.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import assert from 'node:assert/strict'
  2. import { test } from 'node:test'
  3. import { DICT_TYPES } from '../src/modules/cockpit/domain/dictLabels.js'
  4. import {
  5. DICT_SNAPSHOT_VERSION,
  6. buildDictSnapshot,
  7. parseDictSnapshot,
  8. } from '../src/modules/cockpit/domain/dictSnapshot.js'
  9. const sample = () => ({
  10. [DICT_TYPES.riskLevel]: { 0: '重大风险', 1: '较大风险' },
  11. [DICT_TYPES.riskColor]: { 0: '红', 1: '橙' },
  12. })
  13. test('快照带版本、保存时间与按类型的字典表', () => {
  14. const snapshot = buildDictSnapshot(sample(), 1700000000000)
  15. assert.equal(snapshot.version, DICT_SNAPSHOT_VERSION)
  16. assert.equal(snapshot.savedAt, 1700000000000)
  17. assert.deepEqual(snapshot.types[DICT_TYPES.riskLevel], { 0: '重大风险', 1: '较大风险' })
  18. })
  19. test('没有任何字典时不出空快照', () => {
  20. assert.equal(buildDictSnapshot({}), null)
  21. assert.equal(buildDictSnapshot(null), null)
  22. assert.equal(buildDictSnapshot({ [DICT_TYPES.riskLevel]: {} }), null)
  23. })
  24. test('往返:序列化后能解析回同一份字典', () => {
  25. const snapshot = buildDictSnapshot(sample(), 1)
  26. const parsed = parseDictSnapshot(JSON.stringify(snapshot))
  27. assert.deepEqual(parsed.types, snapshot.types)
  28. })
  29. test('版本不符、结构损坏、非法 JSON 都当作没有快照', () => {
  30. const snapshot = buildDictSnapshot(sample(), 1)
  31. assert.equal(parseDictSnapshot(JSON.stringify({ ...snapshot, version: 0 })), null)
  32. assert.equal(parseDictSnapshot('{not json'), null)
  33. assert.equal(parseDictSnapshot(JSON.stringify({ version: DICT_SNAPSHOT_VERSION })), null)
  34. assert.equal(parseDictSnapshot(JSON.stringify({ version: DICT_SNAPSHOT_VERSION, types: [] })), null)
  35. assert.equal(parseDictSnapshot(null), null)
  36. })
  37. test('快照里认不出的类型被丢弃,其余保留', () => {
  38. const parsed = parseDictSnapshot({
  39. version: DICT_SNAPSHOT_VERSION,
  40. savedAt: 5,
  41. types: { [DICT_TYPES.riskLevel]: { 0: '重大风险' }, pump_station_type: { 0: '供水泵站' } },
  42. })
  43. assert.deepEqual(Object.keys(parsed.types), [DICT_TYPES.riskLevel])
  44. })