测试 stores

从设计上讲,stores将在许多地方被使用,并且会使测试变得比应该的困难得多。幸运的是,事实并非如此。在测试stores时,我们需要注意以下三点:

  • Pinia实例:没有它,stores就无法运作
  • Actions:大多数时候,它们包含了stores最复杂的逻辑。如果他们默认被模拟不是很好吗?
  • Plugins:如果您依赖于插件,您也必须安装它们并进行测试

根据您测试的内容或方式,我们需要以不同的方式处理这三个问题:

单元测试 Store

要对store进行单元测试,最重要的部分是创建pinia实例:

  1. // counterStore.spec.ts
  2. import { setActivePinia, createPinia } from 'pinia'
  3. import { useCounter } from '../src/stores/counter'
  4. describe('Counter Store', () => {
  5. beforeEach(() => {
  6. // creates a fresh pinia and make it active so it's automatically picked
  7. // up by any useStore() call without having to pass it to it:
  8. // `useStore(pinia)`
  9. setActivePinia(createPinia())
  10. })
  11. it('increments', () => {
  12. const counter = useCounter()
  13. expect(counter.n).toBe(0)
  14. counter.increment()
  15. expect(counter.n).toBe(1)
  16. })
  17. it('increments by amount', () => {
  18. const counter = useCounter()
  19. counter.increment(10)
  20. expect(counter.n).toBe(10)
  21. })
  22. })

如果您有使用store插件,有一件重要的事情要知道:在应用安装pinia之前,插件不会被使用。可以通过创建一个空应用或假应用来解决:

  1. import { setActivePinia, createPinia } from 'pinia'
  2. import { createApp } from 'vue'
  3. import { somePlugin } from '../src/stores/plugin'
  4. // same code as above...
  5. // you don't need to create one app per test
  6. const app = createApp({})
  7. beforeEach(() => {
  8. const pinia = createPinia().use(somePlugin)
  9. app.use(pinia)
  10. setActivePinia(pinia)
  11. })

单元测试组件

可以通过 createTestingPinia()实现。我还没有为它编写合适的文档,但是可以通过自动补全和出现在工具提示中的文档来理解它的用法。

从安装@pinia/testing开始:

  1. npm i -D @pinia/testing

当组件挂载时,请确保在测试中创建一个测试pinia

  1. import { mount } from '@vue/test-utils'
  2. import { createTestingPinia } from '@pinia/testing'
  3. const wrapper = mount(Counter, {
  4. global: {
  5. plugins: [createTestingPinia()],
  6. },
  7. })
  8. const store = useSomeStore() // uses the testing pinia!
  9. // state can be directly manipulated
  10. store.name = 'my new name'
  11. // can also be done through patch
  12. store.$patch({ name: 'new name' })
  13. expect(store.name).toBe('new name')
  14. // actions are stubbed by default but can be configured by
  15. // passing an option to `createTestingPinia()`
  16. store.someAction()
  17. expect(store.someAction).toHaveBeenCalledTimes(1)
  18. expect(store.someAction).toHaveBeenLastCalledWith()

请注意,如果您使用的是Vue 2@vue/test-utils会有些许不同的配置

您可以在测试包的测试里找到更多示例。

E2E 测试

对于Pinia,您无需为E2E测试更改任何东西,这是E2E测试最重要的点!您也可以测试HTTP请求,但这已经超出了本指南的范围😄。

单元测试组件(Vue 2)

当使Vue Test Utils 1时,在localVue上安装Pinia:

  1. import { PiniaVuePlugin } from 'pinia'
  2. import { createLocalVue, mount } from '@vue/test-utils'
  3. import { createTestingPinia } from '@pinia/testing'
  4. const localVue = createLocalVue()
  5. localVue.use(PiniaVuePlugin)
  6. const wrapper = mount(Counter, {
  7. localVue,
  8. pinia: createTestingPinia(),
  9. })
  10. const store = useSomeStore() // uses the testing pinia!