toDisplayString.spec.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import { toDisplayString } from '../src'
  2. describe('toDisplayString', () => {
  3. test('nullish values', () => {
  4. expect(toDisplayString(null)).toBe('')
  5. expect(toDisplayString(undefined)).toBe('')
  6. })
  7. test('primitive values', () => {
  8. expect(toDisplayString(1)).toBe('1')
  9. expect(toDisplayString(true)).toBe('true')
  10. expect(toDisplayString(false)).toBe('false')
  11. expect(toDisplayString('hello')).toBe('hello')
  12. })
  13. test('Object and Arrays', () => {
  14. const obj = { foo: 123 }
  15. expect(toDisplayString(obj)).toBe(JSON.stringify(obj, null, 2))
  16. const arr = [obj]
  17. expect(toDisplayString(arr)).toBe(JSON.stringify(arr, null, 2))
  18. })
  19. test('native objects', () => {
  20. const div = document.createElement('div')
  21. expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)
  22. expect(toDisplayString({ div })).toMatchInlineSnapshot(`
  23. "{
  24. \\"div\\": \\"[object HTMLDivElement]\\"
  25. }"
  26. `)
  27. })
  28. test('Map and Set', () => {
  29. const m = new Map<any, any>([
  30. [1, 'foo'],
  31. [{ baz: 1 }, { foo: 'bar', qux: 2 }]
  32. ])
  33. const s = new Set<any>([1, { foo: 'bar' }, m])
  34. expect(toDisplayString(m)).toMatchInlineSnapshot(`
  35. "{
  36. \\"Map(2)\\": {
  37. \\"1 =>\\": \\"foo\\",
  38. \\"[object Object] =>\\": {
  39. \\"foo\\": \\"bar\\",
  40. \\"qux\\": 2
  41. }
  42. }
  43. }"
  44. `)
  45. expect(toDisplayString(s)).toMatchInlineSnapshot(`
  46. "{
  47. \\"Set(3)\\": [
  48. 1,
  49. {
  50. \\"foo\\": \\"bar\\"
  51. },
  52. {
  53. \\"Map(2)\\": {
  54. \\"1 =>\\": \\"foo\\",
  55. \\"[object Object] =>\\": {
  56. \\"foo\\": \\"bar\\",
  57. \\"qux\\": 2
  58. }
  59. }
  60. }
  61. ]
  62. }"
  63. `)
  64. expect(
  65. toDisplayString({
  66. m,
  67. s
  68. })
  69. ).toMatchInlineSnapshot(`
  70. "{
  71. \\"m\\": {
  72. \\"Map(2)\\": {
  73. \\"1 =>\\": \\"foo\\",
  74. \\"[object Object] =>\\": {
  75. \\"foo\\": \\"bar\\",
  76. \\"qux\\": 2
  77. }
  78. }
  79. },
  80. \\"s\\": {
  81. \\"Set(3)\\": [
  82. 1,
  83. {
  84. \\"foo\\": \\"bar\\"
  85. },
  86. {
  87. \\"Map(2)\\": {
  88. \\"1 =>\\": \\"foo\\",
  89. \\"[object Object] =>\\": {
  90. \\"foo\\": \\"bar\\",
  91. \\"qux\\": 2
  92. }
  93. }
  94. }
  95. ]
  96. }
  97. }"
  98. `)
  99. })
  100. })