1
0

store.spec.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { haveText, html, test } from '../utils'
  2. test('can register and use a global store',
  3. [html`
  4. <div x-data>
  5. <span x-text="$store.test.foo"></span>
  6. <button @click="$store.test.foo = 'baz'">clickme</button>
  7. </div>
  8. `,
  9. `
  10. Alpine.store('test', { foo: 'bar' })
  11. `],
  12. ({ get }) => {
  13. get('span').should(haveText('bar'))
  14. get('button').click()
  15. get('span').should(haveText('baz'))
  16. }
  17. )
  18. test('store init function is called',
  19. [html`
  20. <div x-data>
  21. <span x-text="$store.test.foo"></span>
  22. <button @click="$store.test.foo = 'baz'">clickme</button>
  23. </div>
  24. `,
  25. `
  26. Alpine.store('test', { foo: 'bar', init() { this.foo = 'baz'} })
  27. `],
  28. ({ get }) => {
  29. get('span').should(haveText('baz'))
  30. }
  31. )
  32. test('can use primitives as store',
  33. [html`
  34. <div x-data>
  35. <span x-text="$store.test"></span>
  36. <button @click="$store.test = 'baz'">clickme</button>
  37. </div>
  38. `,
  39. `
  40. Alpine.store('test', 'bar')
  41. `],
  42. ({ get }) => {
  43. get('span').should(haveText('bar'))
  44. get('button').click()
  45. get('span').should(haveText('baz'))
  46. }
  47. )
  48. test('can use number as store',
  49. [html`
  50. <div x-data>
  51. <span x-text="$store.test"></span>
  52. <button @click="$store.test++">clickme</button>
  53. </div>
  54. `,
  55. `
  56. Alpine.store('test', 0)
  57. `],
  58. ({ get }) => {
  59. get('span').should(haveText('0'))
  60. get('button').click()
  61. get('span').should(haveText('1'))
  62. }
  63. )
  64. test('store\'s "this" context is reactive for init function',
  65. [html`
  66. <div x-data>
  67. <span x-text="$store.test.count"></span>
  68. <button @click="$store.test.increment()" id="button">increment</button>
  69. </div>
  70. `,
  71. `
  72. Alpine.store('test', {
  73. init() {
  74. document.querySelector('#button').addEventListener('click', () => {
  75. this.count++
  76. })
  77. },
  78. count: 0,
  79. })
  80. `],
  81. ({ get }) => {
  82. get('span').should(haveText('0'))
  83. get('button').click()
  84. get('span').should(haveText('1'))
  85. }
  86. )