Skip to content

参考

基于 @pinia/testing v1.x(配 Pinia v3)编写

速查

createTestingPinia(options)

返回 TestingPinia(继承 Pinia,多一个 .app 属性),作为 global.plugins 注入。

TestingOptions

选项默认说明
stubActionstruetrue 全 stub / false 真执行+spy / string[] 选择性 / 函数
initialState{}预设各 store 初始 state(key 为 store id)
stubPatchfalsetrue$patch 被 spy 不改 state
stubResetfalsetrue$reset 被 spy 不重置
plugins[]应用层 Pinia 插件
fakeAppfalse创建空 App 并 app.use(pinia)
createSpy自动spy 工厂(Vitest 无 globals 时传 vi.fn

测试中的 store 能力

操作写法
改 statestore.x = 1 / store.$patch({ ... })
覆盖 getterstore.getterName = value(赋 undefined 恢复)
断言 actionexpect(store.action).toHaveBeenCalledWith(...)
类型安全 mockmockedStore(useStore).action.mockResolvedValue(...)

与 setActivePinia 对照

工具场景
createTestingPinia()组件 + store 集成测试
setActivePinia(createPinia())纯 store 单元测试

官方资源