在使用Vue3进行最激烈的测试时,我很难获得一个使用运行的模拟操作。
我有一个组件,它调用一个模块化的vuex存储,它使用复合api导入到我的组件中。如下所示。
export default defineComponent({
setup() {
const { doAction } = useModActions([
'doAction'
])
}
})
我使用createNamespacedHelpers
从vuex-复合帮助程序库中设置我的存储模块。
在使用带有useStore
键的Symbol
键来设置存储状态之后。在我的应用程序中使用它
app.use(store, key)
为了在我的测试中模拟它,我尝试了以下步骤
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 }
}
})
但是我的间谍从不被调用,我的组件总是调用原始的实现。有办法让所有这些部件一起工作吗?
发布于 2022-04-19 05:06:31
此处的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()
})
})
https://stackoverflow.com/questions/71913777
复制相似问题