Open History to see the last commit
1import { flushSync } from 'svelte'
2import { describe, expect, it, vi } from 'vitest'
3import { watchChanges } from '../src/utils.svelte.js'
4import { ref, withEffectRoot } from './utils.svelte.js'
5β
6describe('watchChanges', () => {
7 it(
8 'should skip the first run and only call the effect on subsequent changes',
9 withEffectRoot(() => {
10 const source = ref(0)
11 const effect = vi.fn()
12β
13 watchChanges(() => source.value, 'pre', effect)
14β
15 // first run only records previousValues, effect is not called
16 flushSync()
17 expect(effect).not.toHaveBeenCalled()
18β
19 source.value = 1
20 flushSync()
21 expect(effect).toHaveBeenCalledExactlyOnceWith(1, 0)
22 }),
23 )
24β
25 it(
26 'should run with the "post" flush timing',
27 withEffectRoot(() => {
28 const source = ref(0)
29 const effect = vi.fn()
30β
31 watchChanges(() => source.value, 'post', effect)
32β
33 flushSync()
34 expect(effect).not.toHaveBeenCalled()
35β
36 source.value = 1
37 flushSync()
38 expect(effect).toHaveBeenCalledExactlyOnceWith(1, 0)
39 }),
40 )
41β
42 it(
43 'should track an array of sources and pass arrays of values',
44 withEffectRoot(() => {
45 const a = ref(1)
46 const b = ref(2)
47 const effect = vi.fn()
48β
49 watchChanges([() => a.value, () => b.value], 'pre', effect)
50β
51 flushSync()
52 expect(effect).not.toHaveBeenCalled()
53β
54 a.value = 10
55 flushSync()
56 expect(effect).toHaveBeenCalledExactlyOnceWith([10, 2], [1, 2])
57 }),
58 )
59β
60 it(
61 'should run the returned cleanup before the next effect run',
62 withEffectRoot(() => {
63 const source = ref(0)
64 const cleanup = vi.fn()
65 const effect = vi.fn(() => cleanup)
66β
67 watchChanges(() => source.value, 'pre', effect)
68β
69 flushSync()
70 source.value = 1
71 flushSync()
72 expect(cleanup).not.toHaveBeenCalled()
73β
74 source.value = 2
75 flushSync()
76 expect(cleanup).toHaveBeenCalledOnce()
77 }),
78 )
79})