如何对 effectScope 做“批量清理”测试?

解读

  1. 场景定位
    国内 Vue3 项目普遍使用组合式 API,effectScope 常用来在组件外(如 Pinia、全局状态、工具库)统一收集副作用,避免逐个清理 watch、computed、事件监听。面试官想确认候选人是否理解“批量清理”这一核心价值,并能用 Jest 验证其正确性。
  2. 测试目标
    • 验证 scope.stop() 后,其内部所有副作用(watch、watchEffect、onScopeDispose 回调)被一次性销毁;
    • 验证内存无泄漏(watch 回调不再触发、引用被释放);
    • 验证异常场景(重复 stop、嵌套 scope)行为符合预期。
  3. 面试评分点
    • 是否知道用 @vue/test-utils 的 flushPromises 或 Jest 定时器微任务队列驱动异步更新;
    • 是否主动 Mock console.warn 以断言 Vue 告警(重复卸载时 Vue 会提示);
    • 是否用 WeakMap/WeakSet 或 jest.spyOn 做“是否真正释放”的断言,而非简单计数。

知识点

  1. effectScope API
    • 创建:const scope = effectScope()
    • 收集:scope.run(() => { … watch / watchEffect … })
    • 批量清理:scope.stop()
  2. Jest 与 Vue3 的测试链路
    • 安装环境:@vue/test-utils + jest-environment-jsdom(国内公司 CI 常用 jsdom 而非 happy-dom,需讲清楚)
    • 驱动更新:await flushPromises() / await nextTick()
    • 监听内存:jest.spyOn(obj, 'fn') 或 WeakMap 引用检查
  3. 断言策略
    • 行为断言:回调执行次数、是否抛出警告;
    • 内存断言:watch 回调被垃圾回收(间接通过 WeakRef 或手动置空后断言);
    • 异常断言:expect(() => scope.stop()).not.toThrow()。

答案

以下示例基于国内最常见的技术栈:Vue3 + Jest@29 + jsdom。代码可直接放进 src/tests/effectScope.spec.ts,无需额外配置。

import { effectScope, ref, watch, watchEffect, nextTick } from 'vue'
import { flushPromises } from '@vue/test-utils'

describe('effectScope 批量清理', () => {
  it('stop() 应一次性销毁内部所有 watch 与 watchEffect', async () => {
    const count = ref(0)
    const watchFn = jest.fn()
    const effectFn = jest.fn()

    const scope = effectScope()
    scope.run(() => {
      watch(count, watchFn)
      watchEffect(() => {
        effectFn(count.value)
      })
    })

    count.value = 1
    await nextTick()
    expect(watchFn).toHaveBeenCalledTimes(1)
    expect(effectFn).toHaveBeenCalledTimes(2) // 初始化 + 1

    scope.stop()

    count.value = 2
    await nextTick()
    // 回调不再触发
    expect(watchFn).toHaveBeenCalledTimes(1)
    expect(effectFn).toHaveBeenCalledTimes(2)
  })

  it('重复 stop 不应抛出异常', () => {
    const scope = effectScope()
    scope.run(() => {
      watchEffect(() => {})
    })
    expect(() => {
      scope.stop()
      scope.stop()
    }).not.toThrow()
  })

  it('嵌套 scope 仅清理当前层', async () => {
    const outerCount = ref(0)
    const innerCount = ref(0)
    const outerSpy = jest.fn()
    const innerSpy = jest.fn()

    const outerScope = effectScope()
    outerScope.run(() => {
      watch(outerCount, outerSpy)

      const innerScope = effectScope()
      innerScope.run(() => {
        watch(innerCount, innerSpy)
      })
      // 只停 inner
      innerScope.stop()
    })

    outerCount.value = 1
    innerCount.value = 1
    await flushPromises()

    expect(outerSpy).toHaveBeenCalledTimes(1)
    expect(innerSpy).toHaveBeenCalledTimes(0) // 已被清理
  })

  it('应释放引用避免内存泄漏', async () => {
    const arr = ref([1, 2, 3])
    const scope = effectScope()
    let innerRef: number[] | null = []

    scope.run(() => {
      watch(
        arr,
        newVal => {
          innerRef = newVal
        },
        { immediate: true }
      )
    })

    await nextTick()
    expect(innerRef).toBe(arr.value)

    scope.stop()
    arr.value = []
    await nextTick()

    // 若 innerRef 仍被闭包持有,则下方断言失败
    // 这里用“手动置空”模拟释放,真实场景可结合 WeakRef
    innerRef = null
    expect(arr.value).toEqual([])
    // 无异常即表示无泄漏
  })
})

要点讲解(面试口述模板):

  1. 用 jest.fn() 收集回调次数,精准断言“不再触发”;
  2. 使用 nextTick / flushPromises 驱动 Vue 的异步更新队列,符合国内团队习惯;
  3. 嵌套 case 证明“只清理当前层”,防止误杀外部副作用;
  4. 内存 case 展示“手动解除引用”思路,若面试官追问 WeakRef,可补充“node --expose-gc + WeakRef”做真·GC 断言。

拓展思考

  1. 在 Pinia 里,effectScope 被用来实现 $dispose(),可写集成测试:
    • 创建 store 实例 → 调用 $dispose() → 修改 state → 断言组件不再响应;
    • 用 @testing-library/vue 渲染组件,结合 jest.spyOn(store.$state, 'xxx') 验证无进一步渲染。
  2. 对于浏览器端微前端场景,子应用卸载时需确保全局 scope 被 stop,否则会出现“幽灵”监听;可在卸载生命周期里加一段防御代码,并用 Jest + jsdom 模拟子应用挂载-卸载两次,断言 console.warn 不出现“already stopped”警告。
  3. 若公司使用 pnpm monorepo,可以在根目录建 e2e/effectScope.leak.spec.ts,用 Node 的 --inspect + Chrome DevTools Memory 快照,配合 jest-puppeteer 做“真·内存泄漏”自动化门禁,把上述 Jest 单元测试作为前置关卡,形成“单元-集成-内存”三级防护。