Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.svelte.test.ts

79 lines1.9 KB

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})