javascript / expert
Snippet
Unit Testing Composables using EffectScope and Isolated Lifecycle Harness
Testing Vue Composition API functions outside of component trees often leads to memory leaks or broken lifecycle registrations. By utilizing Vue's effectScope API inside a test harness helper, composable logic runs within a dedicated, isolated reactive scope. This allows unit test scripts to inspect reactive state mutations directly and explicitly invoke scope.stop() to clear watchers and computed dependencies between test cases.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { effectScope, ref } from 'vue';function withSetup(composable) {let result;const scope = effectScope();scope.run(() => {result = composable();});return [result, () => scope.stop()];}// Usage in Test:const [state, stopScope] = withSetup(() => {const count = ref(0);const increment = () => count.value++;return { count, increment };});state.increment();console.assert(state.count.value === 1, 'Counter should increment');stopScope();
vue
Breakdown
1
function withSetup(composable) {
Defines a generic harness function that encapsulates composable execution without mounting full DOM nodes.
2
const scope = effectScope();
Instantiates an isolated reactive effect scope capable of capturing all computed signals and watchers.
3
scope.run(() => { result = composable(); });
Executes the target composable within the active effect scope context to establish proper reactivity tracking.
4
return [result, () => scope.stop()];
Returns the computed composable output alongside an explicit teardown function for cleanup in tests.
5
stopScope();
Disposes of all watchers, refs, and sub-effects instantiated inside the scope to prevent cross-test leakage.