1
0

custom-data.spec.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { haveText, html, test } from '../utils'
  2. test('can register custom data providers',
  3. html`
  4. <script>
  5. document.addEventListener('alpine:init', () => {
  6. Alpine.data('test', () => ({
  7. foo: 'bar'
  8. }))
  9. })
  10. </script>
  11. <div x-data="test">
  12. <span x-text="foo"></span>
  13. </div>
  14. `,
  15. ({ get }) => get('span').should(haveText('bar'))
  16. )
  17. test.only('can accept initial params',
  18. html`
  19. <script>
  20. document.addEventListener('alpine:init', () => {
  21. Alpine.data('test', (first, second) => ({
  22. foo: first,
  23. bar: second,
  24. }))
  25. })
  26. </script>
  27. <div x-data="test('baz', 'bob')">
  28. <h1 x-text="foo"></h1>
  29. <h2 x-text="bar"></h2>
  30. </div>
  31. `,
  32. ({ get }) => {
  33. get('h1').should(haveText('baz'))
  34. get('h2').should(haveText('bob'))
  35. }
  36. )
  37. test.only('can spread together',
  38. html`
  39. <script>
  40. document.addEventListener('alpine:init', () => {
  41. Alpine.data('test', (first) => ({
  42. foo: first,
  43. }))
  44. Alpine.data('test2', (second) => ({
  45. bar: second,
  46. }))
  47. })
  48. </script>
  49. <div x-data="{ ...test('baz'), ...test2('bob') }">
  50. <h1 x-text="foo"></h1>
  51. <h2 x-text="bar"></h2>
  52. </div>
  53. `,
  54. ({ get }) => {
  55. get('h1').should(haveText('baz'))
  56. get('h2').should(haveText('bob'))
  57. }
  58. )
  59. test('init functions inside custom datas are called automatically',
  60. html`
  61. <script>
  62. document.addEventListener('alpine:init', () => {
  63. Alpine.data('test', () => ({
  64. init() {
  65. this.foo = 'baz'
  66. },
  67. foo: 'bar'
  68. }))
  69. })
  70. </script>
  71. <div x-data="test">
  72. <span x-text="foo"></span>
  73. </div>
  74. `,
  75. ({ get }) => {
  76. get('span').should(haveText('baz'))
  77. }
  78. )
  79. test('init functions "this" context is reactive',
  80. html`
  81. <script>
  82. document.addEventListener('alpine:init', () => {
  83. Alpine.data('test', () => ({
  84. init() {
  85. window.addEventListener('click', () => {
  86. this.foo = 'baz'
  87. })
  88. },
  89. foo: 'bar'
  90. }))
  91. })
  92. </script>
  93. <div x-data="test">
  94. <span x-text="foo"></span>
  95. <button>click me</button>
  96. </div>
  97. `,
  98. ({ get }) => {
  99. get('span').should(haveText('bar'))
  100. get('button').click()
  101. get('span').should(haveText('baz'))
  102. }
  103. )