如何对 Pinia 的插件做“热重载”测试?

解读

“热重载”在国内前端语境里通常指「不刷新浏览器、不重启 Node 进程,代码变更后立刻生效」。
Pinia 的插件(plugin)本质是一个函数 plugin({ pinia, app, options }),在 createPinia() 之后通过 pinia.use(plugin) 注入。
面试问“热重载测试”,不是让你去验证 Vite/HMR 协议本身,而是考察:

  1. 插件在源码被替换后,是否能在「测试运行时」无残留地卸载老逻辑、装载新逻辑;
  2. 新插件是否立即对后续 useStore() 生效;
  3. 旧插件产生的副作用(全局监听、拦截器、定时器)是否被正确清理,避免测试用例交叉污染;
  4. 如何用 Jest 在「秒级」内完成上述验证,满足国内 CI 对单测 3 分钟跑完的要求。

知识点

  1. Pinia 插件系统
    • pinia._p: Plugin[] 私有数组,保存已注册插件;
    • pinia.use(plugin) 会立即执行插件,并把插件 push 进 _p;
    • 插件返回的 dispose 函数会被 Pinia 缓存,用于后续卸载。
  2. HMR 替换流程(源码级)
    • Vite 收到 .js/.ts 变更 → 通过 import.meta.hot.accept() 触发 pinia.hotUpdate();
    • hotUpdate 内部会倒序调用所有插件的 dispose,再重新 use() 新插件。
  3. Jest 运行时“伪热重载”
    • 没有 Vite,需要手动模拟「旧插件卸载→新插件装载」的完整生命周期;
    • 用 createSpy() 监听插件副作用,验证 dispose 是否被调用;
    • 用 jest.resetModules() 或 vi.resetModules()(Vitest 同构)清除模块缓存,防止旧闭包残留。
  4. 测试隔离技巧
    • 每个用例重新 createPinia(),避免单例污染;
    • 对 console.warn/error 做 mockImplementation 断言,防止插件异常被 Jest 吞掉;
    • 使用 done() 或 await waitFor(()=>…) 确保副作用异步完成后再断言。
  5. 覆盖率要求
    • 国内大厂门禁普遍要求单测覆盖率 ≥ 90%,插件分支(如 if (process.env.NODE_ENV !== 'production'))必须覆盖。

答案

下面给出一份可直接跑在 Jest 27+ 的范例,演示“插件热重载”的核心测试点。
目录结构(典型 Vite+Vue3 项目):

src/
└─ stores/
   └─ plugin/
      └─ loggerPlugin.ts
tests/
└─ unit/
   └─ loggerPlugin.hot.test.ts

loggerPlugin.ts

import type { PiniaPluginContext } from 'pinia'

export function loggerPlugin({ store }: PiniaPluginContext) {
  const unwrapped = store.$state
  const handler = (mutation: any) => {
    console.log(`[${store.$id}]`, mutation.type, mutation.payload)
  }
  store.$subscribe(handler)
  // 返回 dispose 用于热重载卸载
  return () => {
    store.$unsubscribe(handler)
    console.log(`[${store.$id}] logger disposed`)
  }
}

loggerPlugin.hot.test.ts

import { createPinia, defineStore, setActivePinia } from 'pinia'
import { loggerPlugin } from '@/stores/plugin/loggerPlugin'

// 工具:快速创建新鲜 pinia
const freshPinia = () => {
  const pinia = createPinia()
  setActivePinia(pinia)
  return pinia
}

describe('loggerPlugin 热重载', () => {
  let pinia: ReturnType<typeof createPinia>
  let consoleSpy: jest.SpyInstance

  beforeEach(() => {
    consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
    pinia = freshPinia()
  })

  afterEach(() => {
    consoleSpy.mockRestore()
  })

  test('插件卸载后不再打印日志', async () => {
    // 1. 装载旧插件
    const dispose = pinia.use(loggerPlugin) as () => void
    const useCounter = defineStore('counter', { state: () => ({ n: 0 }) })
    const store = useCounter()
    store.n++
    await Promise.resolve() // 等待 $subscribe 微任务
    expect(consoleSpy).toHaveBeenCalledWith('[counter]', 'direct', { n: 1 })

    // 2. 模拟热重载:卸载
    dispose()
    consoleSpy.mockClear()

    // 3. 再次变更,应无日志
    store.n++
    await Promise.resolve()
    expect(consoleSpy).not.toHaveBeenCalled()
  })

  test('新插件立即生效且旧副作用被清理', async () => {
    // 1. 旧插件
    const dispose1 = pinia.use(loggerPlugin)
    const useCounter = defineStore('counter', { state: () => ({ n: 0 }) })
    const store = useCounter()
    store.n = 1
    await Promise.resolve()
    const beforeCount = consoleSpy.mock.calls.length

    // 2. 热重载:卸载旧、装载新
    dispose1()
    consoleSpy.mockClear()
    pinia.use(loggerPlugin) // 新插件

    // 3. 再次变更,只应有新插件日志
    store.n = 2
    await Promise.resolve()
    expect(consoleSpy).toHaveBeenCalledTimes(1)
    expect(consoleSpy).toHaveBeenCalledWith('[counter]', 'direct', { n: 2 })
  })

  test('模块缓存重置后插件无残留', () => {
    // 模拟文件变动后重新 import
    jest.resetModules()
    const { loggerPlugin: newLogger } = require('@/stores/plugin/loggerPlugin')
    const pinia2 = freshPinia()
    const dispose = pinia2.use(newLogger)
    expect(typeof dispose).toBe('function')
    dispose()
    // 再次 use 不应报错
    expect(() => pinia2.use(newLogger)).not.toThrow()
  })
})

跑 npm test loggerPlugin.hot.test.ts,3 个用例全部通过即完成“热重载”核心验证。
CI 脚本里再加 --coverage --coverageThreshold='{"global":{"branches":90,"functions":90,"lines":90}}' 即可满足国内主流门禁。

拓展思考

  1. 如果插件内部用 setInterval 或 addEventListener,dispose 需要一并清理,测试里可用 jest.useFakeTimers 与 jest.spyOn(window, 'addEventListener') 双重断言。
  2. 对于「持久化插件」(如 pinia-plugin-persistedstate),热重载时需确认旧插件的 beforeRestore/afterRestore 钩子不再触发,防止把过期缓存写回 localStorage。
  3. 在 Vitest 环境,可直接利用 vi.hoisted(()=>…) 与 import.meta.hot 的 mock,实现真正的「文件变动→热更新」集成测试,比 Jest 更接近生产场景。
  4. 若项目采用 Monorepo,插件包与业务包分离,可在 pnpm --filter plugin test:hot 里用 concurrently 同时起「Jest watch + 文件 touch」脚本,模拟真实 HMR 压力,确保插件在 1000 次热替换后无内存泄漏(用 node --expose-gc 打印 process.memoryUsage())。