Vue3 在 vi​​test 中使用 vuex 测试组合 API

non*_*ame 2 vue.js vuex vue-test-utils vuejs3 vitest

我在使用 vitest 进行测试时无法使用 Vue3 运行模拟操作。

我有一个组件,它调用一个模块化的 vuex 存储,该存储使用组合 api 导入到我的组件中。像下面这样的东西。

export default defineComponent({
  setup() {
    const { doAction } = useModActions([
      'doAction'
    ])
  }
})
Run Code Online (Sandbox Code Playgroud)

我用来createNamespacedHelpers从 vuex-composition-helpers 库设置我的商店模块。

在我使用useStore密钥Symbol设置商店状态后。我通过执行以下操作在我的应用程序中使用它

app.use(store, key)
Run Code Online (Sandbox Code Playgroud)

为了在我的测试中模拟它,我正在尝试以下操作

   const actions = {
      doAction: vi.fn()
    }
    const spy = vi.spyOn(actions, 'doAction')
    const mockStore = createStore({
      modules: {
        mod: {
          namespaced: true,
          actions
        }
      }
    })
    const wrapper = mount(Component, {
      global: {
        provide: { [key]: mockStore }
      }
    })
Run Code Online (Sandbox Code Playgroud)

但我的间谍从未被调用,我的组件总是调用原始实现。有没有办法让所有这些部分一起工作?

ton*_*y19 5

这里mockStore(来自 Vuex 的createStore())是 Vue 插件的一个实例,应将其传递给global.plugins安装选项(而不是global.provide):

// MyComponent.spec.js
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { createStore } from 'vuex'
import MyComponent from '../MyComponent.vue'

describe('MyComponent', () => {
  it('button calls doAction', async () => {
    const actions = {
      doAction: vi.fn(),
    }
    const mockStore = createStore({
      modules: {
        myModule: {
          namespaced: true,
          actions,
        },
      },
    })
    const wrapper = mount(MyComponent, {
      global: {
        plugins: [mockStore], // 
      },
    })
    await wrapper.find("button").trigger("click")
    expect(actions.doAction).toHaveBeenCalled()
  })
})
Run Code Online (Sandbox Code Playgroud)

演示