lifecycle.spec.js 2.4 KB

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