utils.spec.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { Position, NodeTypes } from '../src/ast'
  2. import {
  3. getInnerRange,
  4. advancePositionWithClone,
  5. isEmptyExpression
  6. } from '../src/utils'
  7. function p(line: number, column: number, offset: number): Position {
  8. return { column, line, offset }
  9. }
  10. describe('advancePositionWithClone', () => {
  11. test('same line', () => {
  12. const pos = p(1, 1, 0)
  13. const newPos = advancePositionWithClone(pos, 'foo\nbar', 2)
  14. expect(newPos.column).toBe(3)
  15. expect(newPos.line).toBe(1)
  16. expect(newPos.offset).toBe(2)
  17. })
  18. test('same line', () => {
  19. const pos = p(1, 1, 0)
  20. const newPos = advancePositionWithClone(pos, 'foo\nbar', 4)
  21. expect(newPos.column).toBe(1)
  22. expect(newPos.line).toBe(2)
  23. expect(newPos.offset).toBe(4)
  24. })
  25. test('multiple lines', () => {
  26. const pos = p(1, 1, 0)
  27. const newPos = advancePositionWithClone(pos, 'foo\nbar\nbaz', 10)
  28. expect(newPos.column).toBe(3)
  29. expect(newPos.line).toBe(3)
  30. expect(newPos.offset).toBe(10)
  31. })
  32. })
  33. describe('getInnerRange', () => {
  34. const loc1 = {
  35. source: 'foo\nbar\nbaz',
  36. start: p(1, 1, 0),
  37. end: p(3, 3, 11)
  38. }
  39. test('at start', () => {
  40. const loc2 = getInnerRange(loc1, 0, 4)
  41. expect(loc2.start).toEqual(loc1.start)
  42. expect(loc2.end.column).toBe(1)
  43. expect(loc2.end.line).toBe(2)
  44. expect(loc2.end.offset).toBe(4)
  45. })
  46. test('at end', () => {
  47. const loc2 = getInnerRange(loc1, 4)
  48. expect(loc2.start.column).toBe(1)
  49. expect(loc2.start.line).toBe(2)
  50. expect(loc2.start.offset).toBe(4)
  51. expect(loc2.end).toEqual(loc1.end)
  52. })
  53. test('in between', () => {
  54. const loc2 = getInnerRange(loc1, 4, 3)
  55. expect(loc2.start.column).toBe(1)
  56. expect(loc2.start.line).toBe(2)
  57. expect(loc2.start.offset).toBe(4)
  58. expect(loc2.end.column).toBe(4)
  59. expect(loc2.end.line).toBe(2)
  60. expect(loc2.end.offset).toBe(7)
  61. })
  62. })
  63. describe('isEmptyExpression', () => {
  64. test('empty', () => {
  65. expect(
  66. isEmptyExpression({
  67. content: '',
  68. type: NodeTypes.SIMPLE_EXPRESSION,
  69. isStatic: true,
  70. loc: null as any
  71. })
  72. ).toBe(true)
  73. })
  74. test('spaces', () => {
  75. expect(
  76. isEmptyExpression({
  77. content: ' \t ',
  78. type: NodeTypes.SIMPLE_EXPRESSION,
  79. isStatic: true,
  80. loc: null as any
  81. })
  82. ).toBe(true)
  83. })
  84. test('identifier', () => {
  85. expect(
  86. isEmptyExpression({
  87. content: 'foo',
  88. type: NodeTypes.SIMPLE_EXPRESSION,
  89. isStatic: true,
  90. loc: null as any
  91. })
  92. ).toBe(false)
  93. })
  94. })