forked from alpinejs/alpine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlifecycle.spec.js
105 lines (79 loc) · 2.84 KB
/
lifecycle.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import Alpine from 'alpinejs'
import { wait } from '@testing-library/dom'
global.MutationObserver = class {
observe() {}
}
test('x-init', async () => {
var spanValue
window.setSpanValue = (el) => {
spanValue = el.innerHTML
}
document.body.innerHTML = `
<div x-data="{ foo: 'bar' }" x-init="window.setSpanValue($refs.foo)">
<span x-text="foo" x-ref="foo">baz</span>
</div>
`
Alpine.start()
expect(spanValue).toEqual('baz')
})
test('x-init from data function with callback return for "x-mounted" functionality', async () => {
var valueA
var valueB
window.setValueA = (el) => { valueA = el.innerHTML }
window.setValueB = (el) => { valueB = el.innerText }
window.data = function() {
return {
foo: 'bar',
init() {
window.setValueA(this.$refs.foo)
return () => {
window.setValueB(this.$refs.foo)
}
}
}
}
document.body.innerHTML = `
<div x-data="window.data()" x-init="init()">
<span x-text="foo" x-ref="foo">baz</span>
</div>
`
Alpine.start()
expect(valueA).toEqual('baz')
expect(valueB).toEqual('bar')
})
test('callbacks registered within x-init can affect reactive data changes', async () => {
document.body.innerHTML = `
<div x-data="{ bar: 'baz', foo() { this.$refs.foo.addEventListener('click', () => { this.bar = 'bob' }) } }" x-init="foo()">
<button x-ref="foo"></button>
<span x-text="bar"></span>
</div>
`
Alpine.start()
expect(document.querySelector('span').innerText).toEqual('baz')
document.querySelector('button').click()
await wait(() => { expect(document.querySelector('span').innerText).toEqual('bob') })
})
test('callbacks registered within x-init callback can affect reactive data changes', async () => {
document.body.innerHTML = `
<div x-data="{ bar: 'baz', foo() { this.$refs.foo.addEventListener('click', () => { this.bar = 'bob' }) } }" x-init="() => { foo() }">
<button x-ref="foo"></button>
<span x-text="bar"></span>
</div>
`
Alpine.start()
expect(document.querySelector('span').innerText).toEqual('baz')
document.querySelector('button').click()
await wait(() => { expect(document.querySelector('span').innerText).toEqual('bob') })
})
test('x-init is capable of dispatching an event', async () => {
document.body.innerHTML = `
<div x-data="{ foo: 'bar' }" @update-foo="foo = $event.detail.foo">
<div x-data x-init="$dispatch('update-foo', { foo: 'baz' })"></div>
<span x-text="foo"></span>
</div>
`
Alpine.start()
await wait(() => {
expect(document.querySelector('span').innerText).toEqual('baz')
})
})