data.spec.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import Alpine from 'alpinejs'
  2. import { fireEvent, wait } from '@testing-library/dom'
  3. global.MutationObserver = class {
  4. observe() {}
  5. }
  6. test('data manipulated on component object is reactive', async () => {
  7. document.body.innerHTML = `
  8. <div x-data="{ foo: 'bar' }">
  9. <span x-text="foo"></span>
  10. </div>
  11. `
  12. Alpine.start()
  13. document.querySelector('div').__x.$data.foo = 'baz'
  14. await wait(() => { expect(document.querySelector('span').innerText).toEqual('baz') })
  15. })
  16. test('x-data attribute value is optional', async () => {
  17. document.body.innerHTML = `
  18. <div x-data>
  19. <span x-text="'foo'"></span>
  20. </div>
  21. `
  22. Alpine.start()
  23. expect(document.querySelector('span').innerText).toEqual('foo')
  24. })
  25. test('x-data can use attributes from a reusable function', async () => {
  26. document.body.innerHTML = `
  27. <div x-data="test()">
  28. <span x-text="foo"></span>
  29. </div>
  30. `
  31. test = function() {
  32. return {
  33. foo: 'bar',
  34. }
  35. }
  36. Alpine.start()
  37. expect(document.querySelector('span').innerText).toEqual('bar')
  38. })
  39. test('functions in x-data are reactive', async () => {
  40. document.body.innerHTML = `
  41. <div x-data="{ foo: 'bar', getFoo() {return this.foo}}">
  42. <span x-text="getFoo()"></span>
  43. <button x-on:click="foo = 'baz'"></button>
  44. </div>
  45. `
  46. Alpine.start()
  47. expect(document.querySelector('span').innerText).toEqual('bar')
  48. document.querySelector('button').click()
  49. await wait(() => { expect(document.querySelector('span').innerText).toEqual('baz') })
  50. })