javascript / expert
Snippet
Isolated EffectScope Teardown Verification in Unit Tests
This snippet illustrates unit testing of detached Vue reactive scopes using effectScope. By running reactivity side-effects within a scope and calling scope.stop(), developers can verify that observers and watchers are correctly collected and torn down to avoid memory retention during lifecycle cleanup.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { ref, watch, effectScope } from 'vue';import { expect, test } from 'vitest';test('teardown stops reactive subscriptions within effect scope', () => {const scope = effectScope(true);const count = ref(0);let sideEffectCount = 0;scope.run(() => {watch(count, (val) => {sideEffectCount = val * 2;});});count.value = 5;expect(sideEffectCount).toBe(10);scope.stop();count.value = 20;expect(sideEffectCount).toBe(10);});
vue
Breakdown
1
const scope = effectScope(true);
Instantiates a detached Vue reactive scope container independent of active component instances.
2
scope.run(() => {
Executes callback functions while capturing all nested reactive watchers and computed properties automatically.
3
watch(count, (val) => { sideEffectCount = val * 2; });
Registers a reactive dependency watcher inside the explicitly isolated scope boundary.
4
expect(sideEffectCount).toBe(10);
Verifies that reactive watcher updates trigger successfully prior to scope disposal.
5
scope.stop();
Disposes of all child subscriptions and effects registered inside the effect scope simultaneously.
6
expect(sideEffectCount).toBe(10);
Asserts that state mutations after scope stoppage do not fire detached watcher callbacks.