custom-data.spec.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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('init functions inside custom datas are called automatically',
  18. html`
  19. <script>
  20. document.addEventListener('alpine:init', () => {
  21. Alpine.data('test', () => ({
  22. init() {
  23. this.foo = 'baz'
  24. },
  25. foo: 'bar'
  26. }))
  27. })
  28. </script>
  29. <div x-data="test">
  30. <span x-text="foo"></span>
  31. </div>
  32. `,
  33. ({ get }) => {
  34. get('span').should(haveText('baz'))
  35. }
  36. )
  37. test('init functions "this" context is reactive',
  38. html`
  39. <script>
  40. document.addEventListener('alpine:init', () => {
  41. Alpine.data('test', () => ({
  42. init() {
  43. window.addEventListener('click', () => {
  44. this.foo = 'baz'
  45. })
  46. },
  47. foo: 'bar'
  48. }))
  49. })
  50. </script>
  51. <div x-data="test">
  52. <span x-text="foo"></span>
  53. <button>click me</button>
  54. </div>
  55. `,
  56. ({ get }) => {
  57. get('span').should(haveText('bar'))
  58. get('button').click()
  59. get('span').should(haveText('baz'))
  60. }
  61. )