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

utils.svelte.test.ts

97 lines2.4 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 =
12 vi.fn<
13 (
14 values: number | Array<number>,
15 previousValues: number | Array<number | undefined> | undefined,
16 ) => void
17 >()
18​
19 watchChanges(() => source.value, 'pre', effect)
20​
21 // first run only records previousValues, effect is not called
22 flushSync()
23 expect(effect).not.toHaveBeenCalled()
24​
25 source.value = 1
26 flushSync()
27 expect(effect).toHaveBeenCalledExactlyOnceWith(1, 0)
28 }),
29 )
30​
31 it(
32 'should run with the "post" flush timing',
33 withEffectRoot(() => {
34 const source = ref(0)
35 const effect =
36 vi.fn<
37 (
38 values: number | Array<number>,
39 previousValues: number | Array<number | undefined> | undefined,
40 ) => void
41 >()
42​
43 watchChanges(() => source.value, 'post', effect)
44​
45 flushSync()
46 expect(effect).not.toHaveBeenCalled()
47​
48 source.value = 1
49 flushSync()
50 expect(effect).toHaveBeenCalledExactlyOnceWith(1, 0)
51 }),
52 )
53​
54 it(
55 'should track an array of sources and pass arrays of values',
56 withEffectRoot(() => {
57 const a = ref(1)
58 const b = ref(2)
59 const effect =
60 vi.fn<
61 (
62 values: number | Array<number>,
63 previousValues: number | Array<number | undefined> | undefined,
64 ) => void
65 >()
66​
67 watchChanges([() => a.value, () => b.value], 'pre', effect)
68​
69 flushSync()
70 expect(effect).not.toHaveBeenCalled()
71​
72 a.value = 10
73 flushSync()
74 expect(effect).toHaveBeenCalledExactlyOnceWith([10, 2], [1, 2])
75 }),
76 )
77​
78 it(
79 'should run the returned cleanup before the next effect run',
80 withEffectRoot(() => {
81 const source = ref(0)
82 const cleanup = vi.fn<() => void>()
83 const effect = vi.fn<() => () => void>(() => cleanup)
84​
85 watchChanges(() => source.value, 'pre', effect)
86​
87 flushSync()
88 source.value = 1
89 flushSync()
90 expect(cleanup).not.toHaveBeenCalled()
91​
92 source.value = 2
93 flushSync()
94 expect(cleanup).toHaveBeenCalledTimes(1)
95 }),
96 )
97})