x-data.spec.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { haveText, html, test } from '../../utils'
  2. test('x-data attribute value is optional',
  3. html`
  4. <div x-data>
  5. <span x-text="'foo'"></span>
  6. </div>
  7. `,
  8. ({ get }) => get('span').should(haveText('foo'))
  9. )
  10. test('x-data can be nested',
  11. html`
  12. <div x-data="{ foo: 'bar', bar: 'baz' }">
  13. <div x-data="{ bar: 'bob' }">
  14. <h1 x-text="foo"></h1>
  15. <h2 x-text="bar"></h2>
  16. <button id="inner" @click="foo = 'bob'; bar = 'lob'">click</button>
  17. </div>
  18. <h3 x-text="foo"></h3>
  19. <h4 x-text="bar"></h4>
  20. <button id="outer" @click="foo = 'law'; bar = 'blog'">click</button>
  21. </div>
  22. `,
  23. ({ get }) => {
  24. get('h1').should(haveText('bar'))
  25. get('h2').should(haveText('bob'))
  26. get('h3').should(haveText('bar'))
  27. get('h4').should(haveText('baz'))
  28. get('button#inner').click()
  29. get('h1').should(haveText('bob'))
  30. get('h2').should(haveText('lob'))
  31. get('h3').should(haveText('bob'))
  32. get('h4').should(haveText('baz'))
  33. get('button#outer').click()
  34. get('h1').should(haveText('law'))
  35. get('h2').should(haveText('lob'))
  36. get('h3').should(haveText('law'))
  37. get('h4').should(haveText('blog'))
  38. }
  39. )
  40. test('x-data can use attributes from a reusable function',
  41. html`
  42. <script>
  43. window.test = () => {
  44. return {
  45. foo: 'bar'
  46. }
  47. }
  48. </script>
  49. <div x-data="test()">
  50. <span x-text="foo"></span>
  51. </div>
  52. `,
  53. ({ get }) => get('span').should(haveText('bar'))
  54. )
  55. test('x-data can use $el',
  56. html`
  57. <div x-data="{ text: $el.dataset.text }" data-text="test">
  58. <span x-text="text"></span>
  59. </div>
  60. `,
  61. ({ get }) => get('span').should(haveText('test'))
  62. )
  63. test('functions in x-data are reactive',
  64. html`
  65. <div x-data="{ foo: 'bar', getFoo() {return this.foo}}">
  66. <span x-text="getFoo()"></span>
  67. <button x-on:click="foo = 'baz'">click me</button>
  68. </div>
  69. `,
  70. ({ get }) => {
  71. get('span').should(haveText('bar'))
  72. get('button').click()
  73. get('span').should(haveText('baz'))
  74. }
  75. )
  76. test('functions in x-data have access to proper this context',
  77. html`
  78. <div x-data="{ foo: undefined, change() { this.foo = 'baz' }}" x-init="foo = 'bar'">
  79. <button @click="change()">change</button>
  80. <span x-text="foo"></span>
  81. </div>
  82. `,
  83. ({ get }) => {
  84. get('span').should(haveText('bar'))
  85. get('button').click()
  86. get('span').should(haveText('baz'))
  87. }
  88. )