x-if.spec.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { beVisible, haveText, html, notBeVisible, test } from '../../utils'
  2. test('x-if',
  3. html`
  4. <div x-data="{ show: false }">
  5. <button @click="show = ! show">Toggle</button>
  6. <template x-if="show">
  7. <h1>Toggle Me</h1>
  8. </template>
  9. </div>
  10. `,
  11. ({ get }) => {
  12. get('h1').should(notBeVisible())
  13. get('button').click()
  14. get('h1').should(beVisible())
  15. get('button').click()
  16. get('h1').should(notBeVisible())
  17. }
  18. )
  19. test('x-if inside x-for allows nested directives',
  20. html`
  21. <div x-data="{items: [{id: 1, label: '1'}]}">
  22. <template x-for="item in items" :key="item.id">
  23. <div>
  24. <template x-if="item.label">
  25. <span x-text="item.label"></span>
  26. </template>
  27. </div>
  28. </template>
  29. </div>
  30. `,
  31. ({ get }) => {
  32. get('span').should(haveText('1'))
  33. }
  34. )
  35. test('x-if initializes after being added to the DOM to allow x-ref to work',
  36. html`
  37. <div x-data="{}">
  38. <template x-if="true">
  39. <ul x-ref="listbox" data-foo="bar">
  40. <li x-text="$refs.listbox.dataset.foo"></li>
  41. </ul>
  42. </template>
  43. </div>
  44. `,
  45. ({ get }) => {
  46. get('li').should(haveText('bar'))
  47. }
  48. )
  49. // If x-if evaluates to false, the expectation is that no sub-expressions will be evaluated.
  50. test('x-if removed dom does not evaluate reactive expressions in dom tree',
  51. html`
  52. <div x-data="{user: {name: 'lebowski'}}">
  53. <button @click="user = null">Log out</button>
  54. <template x-if="user">
  55. <span x-text="user.name"></span>
  56. </template>
  57. </div>
  58. `,
  59. ({ get }) => {
  60. get('span').should(haveText('lebowski'))
  61. // Clicking button sets user=null and thus x-if="user" will evaluate to false.
  62. // If the sub-expression x-text="user.name" is evaluated, the button click
  63. // will produce an error because user is no longer defined and the test will fail
  64. get('button').click()
  65. get('span').should('not.exist')
  66. }
  67. )