lifecycle.spec.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import Alpine from 'alpinejs'
  2. import { wait } from '@testing-library/dom'
  3. global.MutationObserver = class {
  4. observe() {}
  5. }
  6. test('x-created', async () => {
  7. var spanValue
  8. window.setSpanValue = (el) => {
  9. spanValue = el.innerHTML
  10. }
  11. document.body.innerHTML = `
  12. <div x-data="{ foo: 'bar' }" x-created="window.setSpanValue($refs.foo)">
  13. <span x-text="foo" x-ref="foo">baz</span>
  14. </div>
  15. `
  16. Alpine.start()
  17. expect(spanValue).toEqual('baz')
  18. })
  19. test('x-mounted', async () => {
  20. var spanValue
  21. window.setSpanValue = (el) => {
  22. spanValue = el.innerText
  23. }
  24. document.body.innerHTML = `
  25. <div x-data="{ foo: 'bar' }" x-mounted="window.setSpanValue($refs.foo)">
  26. <span x-text="foo" x-ref="foo">baz</span>
  27. </div>
  28. `
  29. Alpine.start()
  30. expect(spanValue).toEqual('bar')
  31. })
  32. test('callbacks registered within x-created can affect reactive data changes', async () => {
  33. document.body.innerHTML = `
  34. <div x-data="{ bar: 'baz', foo() { this.$refs.foo.addEventListener('click', () => { this.bar = 'bob' }) } }" x-created="foo()">
  35. <button x-ref="foo"></button>
  36. <span x-text="bar"></span>
  37. </div>
  38. `
  39. Alpine.start()
  40. expect(document.querySelector('span').innerText).toEqual('baz')
  41. document.querySelector('button').click()
  42. await wait(() => { expect(document.querySelector('span').innerText).toEqual('bob') })
  43. })
  44. test('callbacks registered within x-mounted can affect reactive data changes', async () => {
  45. document.body.innerHTML = `
  46. <div x-data="{ bar: 'baz', foo() { this.$refs.foo.addEventListener('click', () => { this.bar = 'bob' }) } }" x-mounted="foo()">
  47. <button x-ref="foo"></button>
  48. <span x-text="bar"></span>
  49. </div>
  50. `
  51. Alpine.start()
  52. expect(document.querySelector('span').innerText).toEqual('baz')
  53. document.querySelector('button').click()
  54. await wait(() => { expect(document.querySelector('span').innerText).toEqual('bob') })
  55. })