Skip to content

Commit 8f4d679

Browse files
committed
test: add test
1 parent de85527 commit 8f4d679

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

packages/reactivity/__tests__/watch.spec.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@ import {
55
type WatchOptions,
66
type WatchScheduler,
77
computed,
8+
effectScope,
89
onWatcherCleanup,
910
ref,
1011
watch,
1112
} from '../src'
13+
import { expect } from 'vitest'
1214

1315
const queue: (() => void)[] = []
1416

@@ -277,4 +279,44 @@ describe('watch', () => {
277279

278280
expect(dummy).toEqual([1, 2, 3])
279281
})
282+
283+
test('removing a watcher while stopping its effectScope', async () => {
284+
const count = ref(0)
285+
const scope = effectScope()
286+
let watcherCalls = 0
287+
let cleanupCalls = 0
288+
289+
scope.run(() => {
290+
const stop1 = watch(count, () => {
291+
watcherCalls++
292+
})
293+
watch(count, (val, old, onCleanup) => {
294+
watcherCalls++
295+
onCleanup(() => {
296+
cleanupCalls++
297+
stop1()
298+
})
299+
})
300+
watch(count, () => {
301+
watcherCalls++
302+
})
303+
})
304+
305+
expect(watcherCalls).toBe(0)
306+
expect(cleanupCalls).toBe(0)
307+
308+
count.value++
309+
await nextTick()
310+
expect(watcherCalls).toBe(3)
311+
expect(cleanupCalls).toBe(0)
312+
313+
scope.stop()
314+
count.value++
315+
await nextTick()
316+
expect(watcherCalls).toBe(3)
317+
expect(cleanupCalls).toBe(1)
318+
319+
expect(scope.effects.length).toBe(0)
320+
expect(scope.cleanups.length).toBe(0)
321+
})
280322
})

packages/reactivity/src/effectScope.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,9 @@ export class EffectScope {
118118
stop(fromParent?: boolean): void {
119119
if (this._active) {
120120
let i, l
121-
for (i = 0, l = this.effects.length; i < l; i++) {
122-
this.effects[i].stop()
121+
const effects = this.effects.slice()
122+
for (i = 0, l = effects.length; i < l; i++) {
123+
effects[i].stop()
123124
}
124125
const cleanups = this.cleanups.slice()
125126
for (i = 0, l = cleanups.length; i < l; i++) {

0 commit comments

Comments
 (0)