text_spec.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var textParser = require('../../../../src/parse/text')
  2. var config = require('../../../../src/config')
  3. var testCases = [
  4. {
  5. // no tags
  6. text: 'haha',
  7. expected: null
  8. },
  9. {
  10. // basic
  11. text: 'a {{ a }} c',
  12. expected: [
  13. { value: 'a ' },
  14. { tag: true, value: 'a', html: false, oneTime: false },
  15. { value: ' c' }
  16. ]
  17. },
  18. {
  19. // html
  20. text: '{{ text }} and {{{ html }}}',
  21. expected: [
  22. { tag: true, value: 'text', html: false, oneTime: false },
  23. { value: ' and ' },
  24. { tag: true, value: 'html', html: true, oneTime: false },
  25. ]
  26. },
  27. {
  28. // one time
  29. text: '{{* text }} and {{{* html }}}',
  30. expected: [
  31. { tag: true, value: 'text', html: false, oneTime: true },
  32. { value: ' and ' },
  33. { tag: true, value: 'html', html: true, oneTime: true },
  34. ]
  35. },
  36. {
  37. // partial
  38. text: '{{> hello }} and {{>hello}}',
  39. expected: [
  40. { tag: true, value: 'hello', html: false, oneTime: false, partial: true },
  41. { value: ' and ' },
  42. { tag: true, value: 'hello', html: false, oneTime: false, partial: true }
  43. ]
  44. }
  45. ]
  46. function assertParse (test) {
  47. var res = textParser.parse(test.text)
  48. var exp = test.expected
  49. if (!Array.isArray(exp)) {
  50. expect(res).toBe(exp)
  51. } else {
  52. expect(res.length).toBe(exp.length)
  53. res.forEach(function (r, i) {
  54. var e = exp[i]
  55. for (var key in e) {
  56. expect(e[key]).toEqual(r[key])
  57. }
  58. })
  59. }
  60. }
  61. describe('Text Parser', function () {
  62. it('parse', function () {
  63. testCases.forEach(assertParse)
  64. })
  65. it('cache', function () {
  66. var res1 = textParser.parse('{{a}}')
  67. var res2 = textParser.parse('{{a}}')
  68. expect(res1).toBe(res2)
  69. })
  70. it('custom delimiters', function () {
  71. config.delimiters = ['[%', '%]']
  72. assertParse({
  73. text: '[%* text %] and [[% html %]]',
  74. expected: [
  75. { tag: true, value: 'text', html: false, oneTime: true },
  76. { value: ' and ' },
  77. { tag: true, value: 'html', html: true, oneTime: false },
  78. ]
  79. })
  80. config.delimiters = ['{{', '}}']
  81. })
  82. it('tokens to expression', function () {
  83. var tokens = textParser.parse('view-{{test}}-test-{{ok}}')
  84. var exp = textParser.tokensToExp(tokens)
  85. expect(exp).toBe('"view-"+test+"-test-"+ok')
  86. })
  87. })