store 测试
从设计上来说,许多地方都会使用 store,所以可能比正常情况更难测试。但幸运的是,这不一定是真的。在测试 store 时,我们需要注意三件事:
pinia实例:没有它,store 不能正常工作actions:大多数时候,它们包含了 store 最复杂的逻辑。如果它们默认就可以被 mocked,那不是很好吗?- 插件:如果你依赖插件,你也必须为测试安装它们
根据测试的内容和方式,我们需要以不同的方式来处理这三个问题。
对 store 进行单元测试
要对一个 store 进行单元测试,最重要的是创建一个 pinia 实例:
// stores/counter.spec.ts
import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '../src/stores/counter'
describe('Counter Store', () => {
beforeEach(() => {
// 创建一个新 pinia,并使其处于激活状态,这样它就会被任何 useStore() 调用自动接收
// 而不需要手动传递:
// `useStore(pinia)`
setActivePinia(createPinia())
})
it('increments', () => {
const counter = useCounterStore()
expect(counter.n).toBe(0)
counter.increment()
expect(counter.n).toBe(1)
})
it('increments by amount', () => {
const counter = useCounterStore()
counter.increment(10)
expect(counter.n).toBe(10)
})
})如果你有使用任何 store 的插件,有一件重要的事情需要了解:在 pinia 被安装在一个应用之后,插件才会被使用。可以通过创建一个空的或假的应用来解决这个问题:
import { setActivePinia, createPinia } from 'pinia'
import { createApp } from 'vue'
import { somePlugin } from '../src/stores/plugin'
// 和前面一样的代码...
// 你不需要为每个测试创建一个应用
const app = createApp({})
beforeEach(() => {
const pinia = createPinia().use(somePlugin)
app.use(pinia)
setActivePinia(pinia)
})对组件单元测试
这可以通过 createTestingPinia() 实现,它会返回一个仅用于帮助对组件单元测试的 pinia 实例。
从安装 @pinia/testing 开始:
npm i -D @pinia/testing确保挂载组件时,在你的测试中创建一个用于测试的 pinia 实例:
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'
// 引入任何你想要测试的 store
import { useSomeStore } from '@/stores/myStore'
const wrapper = mount(Counter, {
global: {
plugins: [createTestingPinia()],
},
})
const store = useSomeStore() // 使用 pinia 的测试实例!
// 可直接操作 state
store.name = 'my new name'
// 也可以通过 patch 来完成
store.$patch({ name: 'new name' })
expect(store.name).toBe('new name')
// action 默认是存根的(stubbed),意味着它们默认不执行其代码。
// 请看下面的内容来定制这一行为。
store.someAction()
expect(store.someAction).toHaveBeenCalledTimes(1)
expect(store.someAction).toHaveBeenLastCalledWith()初始 State
在创建测试 Pinia 时,你可以通过传递一个 initialState 对象来设置所有 store 的初始状态。这个对象将被 pinia 的测试实例用于创建 store 时 patch store。比方说,你想初始化这个 store 的状态:
import { defineStore } from 'pinia'
const useCounterStore = defineStore('counter', {
state: () => ({ n: 0 }),
// ...
})由于 store 的名字是 "counter",所以你需要传递相应的对象给 initialState:
// 在测试中的某处
const wrapper = mount(Counter, {
global: {
plugins: [
createTestingPinia({
initialState: {
counter: { n: 20 }, // 从 20 开始计数,而不是 0
},
}),
],
},
})
const store = useSomeStore() // 使用 pinia 的测试实例!
store.n // 20自定义 action 的行为
除非另有指示,createTestingPinia 会存根 (stub) 出所有的 store action。这样可以让你独立测试你的组件和 store。
如果你想恢复这种行为,并在测试中正常执行 action,请在调用 createTestingPinia 时指定 stubActions: false:
const wrapper = mount(Counter, {
global: {
plugins: [createTestingPinia({ stubActions: false })],
},
})
const store = useSomeStore()
// 现在,这个调用将由 store 定义的实现执行。
store.someAction()
// ...但它仍然被一个 spy 包装着,所以你可以检查调用
expect(store.someAction).toHaveBeenCalledTimes(1)Setup store 中的存根限制
stubActions 只会替换 store 实例上的 action。在 Setup store 中,一个 action 调用另一个 action 时,使用的是闭包中的函数引用,而不是 store,所以这个内部调用永远不会用到存根:
// Setup store
export const useCounterStore = defineStore('counter', () => {
function increment() {
/* ... */
}
function incrementTwice() {
increment() // ❌ 闭包中的引用,永远不会用到存根
increment()
}
return { increment, incrementTwice }
})存根会影响 store.increment(),但不会影响 incrementTwice() 内部的 increment() 调用。执行真正的 incrementTwice() 时,总是会执行真正的 increment()。
Option store 没有这个限制。内部调用会经过 this,也就是 store 实例,所以它们会调用存根:
// Option store
export const useCounterStore = defineStore('counter', {
actions: {
increment() {
/* ... */
},
incrementTwice() {
this.increment() // ✅ 经过 store,使用存根
this.increment()
},
},
})WARNING
要让 Setup store 中的内部调用可以被存根,请通过 store 来调用,而不是使用闭包中的函数:
export const useCounterStore = defineStore('counter', () => {
function increment() {
/* ... */
}
function incrementTwice() {
const store = useCounterStore()
store.increment() // ✅ 经过 store,使用存根
store.increment()
}
return { increment, incrementTwice }
})这样做是可行的,但仅仅为了满足测试而这样做有些 小题大做。所以请先重新考虑一下,你是否真的需要存根这个 action,或者能否直接测试它真正的实现。
选择性 action 存根
有时你可能只想存根特定的 action,而让其他 action 正常执行。你可以通过向 stubActions 选项传递一个 action 名称数组来实现:
// 只存根 'increment' 和 'reset' action
const wrapper = mount(Counter, {
global: {
plugins: [
createTestingPinia({
stubActions: ['increment', 'reset'],
}),
],
},
})
const store = useSomeStore()
// 这些 action 将被存根(不执行)
store.increment() // 存根
store.reset() // 存根
// 其他 action 将正常执行但仍被监听
store.fetchData() // 正常执行
expect(store.fetchData).toHaveBeenCalledTimes(1)对于更复杂的场景,你可以传递一个函数,该函数接收 action 名称和 store 实例,并返回是否应该存根该 action:
// 基于自定义逻辑存根 action
const wrapper = mount(Counter, {
global: {
plugins: [
createTestingPinia({
stubActions: (actionName, store) => {
// 存根所有以 'set' 开头的 action
if (actionName.startsWith('set')) return true
// 根据初始 store 状态存根 action
if (store.isPremium) return false
return true
},
}),
],
},
})
const store = useSomeStore()
// 以 'set' 开头的 action 被存根
store.setValue(42) // 存根
// 其他 action 可能根据初始 store 状态执行
store.fetchData() // 根据初始 store.isPremium 执行或存根TIP
- 空数组
[]表示不存根任何 action(与false相同) - 函数在 store 设置时被评估一次,接收处于初始状态的 store 实例
你也可以在创建 store 后手动模拟特定的 action:
const store = useSomeStore()
vi.spyOn(store, 'increment').mockImplementation(() => {})
// 或者如果使用带有存根 action 的测试 pinia
store.increment.mockImplementation(() => {})Mock action 的返回值
action 会被自动监听 (spy),但在类型上,它们仍然是常规的 action。为了获得正确的类型,我们必须实现一个自定义的类型包装器,将 Mock 类型应用到每个 action 上。这个类型取决于你所使用的测试框架。下面是一个使用 Vitest 的例子:
import type { Mock } from 'vitest'
import type { UnwrapRef } from 'vue'
import type { Store, StoreDefinition } from 'pinia'
function mockedStore<TStoreDef extends () => unknown>(
useStore: TStoreDef
): TStoreDef extends StoreDefinition<
infer Id,
infer State,
infer Getters,
infer Actions
>
? Store<
Id,
State,
Record<string, never>,
{
[K in keyof Actions]: Actions[K] extends (...args: any[]) => any
? // 👇 取决于你的测试框架
Mock<Actions[K]>
: Actions[K]
}
> & {
[K in keyof Getters]: UnwrapRef<Getters[K]>
}
: ReturnType<TStoreDef> {
return useStore() as any
}它可以在测试中用来获得一个类型正确的 store:
import { mockedStore } from './mockedStore'
import { useSomeStore } from '@/stores/myStore'
const store = mockedStore(useSomeStore)
// 有类型了!
store.someAction.mockResolvedValue('some value')如果你有兴趣学习更多类似的技巧,可以看看 Mastering Pinia 中的测试课程。
指定 createSpy 函数
当使用 Jest,或 vitest 且设置 globals: true 时,createTestingPinia 会自动使用现有测试框架 (jest.fn 或 vitest.fn) 的 spy 函数存根 (stub) action。如果你没有设置 globals: true,或者使用的是不同的框架,你需要提供一个 createSpy 选项:
// 注意:设置了 `globals: true` 时不需要这样做
import { vi } from 'vitest'
createTestingPinia({
createSpy: vi.fn,
})import sinon from 'sinon'
createTestingPinia({
createSpy: sinon.spy,
})你可以在测试包的测试源码中找到更多的例子。
Mocking getters
默认情况下,任何 getter 都会像常规用法一样进行计算,但你可以通过将 getter 设置为任何你想要的值来手动强制计算:
import { defineStore } from 'pinia'
import { createTestingPinia } from '@pinia/testing'
const useCounterStore = defineStore('counter', {
state: () => ({ n: 1 }),
getters: {
double: (state) => state.n * 2,
},
})
const pinia = createTestingPinia()
const counter = useCounterStore(pinia)
counter.double = 3 // 🪄 getter 仅在测试中可被重写
// 设置为 undefined,以重置默认行为
// @ts-expect-error: usually it's a number
counter.double = undefined
counter.double // 2 (=1 x 2)Pinia 插件
如果你有使用任何 pinia 插件,确保在调用 createTestingPinia() 时传入它们,这样它们就会被正确加载。不要使用 testingPinia.use(MyPlugin) 来加载它们,而应该像正常的 pinia 那样:
import { createTestingPinia } from '@pinia/testing'
import { somePlugin } from '../src/stores/plugin'
// 在某个测试中
const wrapper = mount(Counter, {
global: {
plugins: [
createTestingPinia({
stubActions: false,
plugins: [somePlugin],
}),
],
},
})Nuxt
如果你在测试一个 Nuxt 应用,请参考 在 Nuxt 中测试。
端到端测试
对于 pinia,你不需要为端到端测试修改任何代码,这就是端到端测试的含义!也许你想测试 HTTP 请求,但这已经超出了本指南的范围😄。
