custom-directives.spec.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { haveText, haveAttribute, html, test } from '../utils'
  2. test('can register custom directive',
  3. [html`
  4. <div x-data>
  5. <span x-foo:bar.baz="bob"></span>
  6. </div>
  7. `,
  8. `
  9. Alpine.directive('foo', (el, { value, modifiers, expression }) => {
  10. el.textContent = value+modifiers+expression
  11. })
  12. `],
  13. ({ get }) => get('span').should(haveText('barbazbob'))
  14. )
  15. test('directives are auto cleaned up',
  16. [html`
  17. <div x-data="{ count: 0 }">
  18. <span x-foo x-ref="foo"></span>
  19. <h1 x-text="count"></h1>
  20. <button @click="count++" id="change">change</button>
  21. <button @click="$refs.foo.remove()" id="remove">remove</button>
  22. </div>
  23. `,
  24. `
  25. Alpine.directive('foo', (el, {}, { effect, cleanup, evaluateLater }) => {
  26. let incCount = evaluateLater('count++')
  27. cleanup(() => {
  28. incCount()
  29. incCount()
  30. })
  31. effect(() => {
  32. incCount()
  33. })
  34. })
  35. `],
  36. ({ get }) => {
  37. get('h1').should(haveText('1'))
  38. get('#change').click()
  39. get('h1').should(haveText('3'))
  40. get('#remove').click()
  41. get('#change').click()
  42. get('h1').should(haveText('6'))
  43. get('#change').click()
  44. get('h1').should(haveText('7'))
  45. }
  46. )
  47. test('can register a custom directive before an existing one',
  48. [html`
  49. <div x-data>
  50. <span x-foo x-bind:foo="foo"></span>
  51. </div>
  52. `,
  53. `
  54. Alpine.directive('foo', (el, { value, modifiers, expression }) => {
  55. Alpine.addScopeToNode(el, {foo: 'bar'})
  56. }).before('bind')
  57. `],
  58. ({ get }) => get('span').should(haveAttribute('foo', 'bar'))
  59. )