【发布时间】:2020-10-30 21:03:38
【问题描述】:
阅读了大量的 stackoverflow 和 github 讨论,关于 vue jest 遇到 button.trigger('click') 的问题。我今天已经为这个问题苦苦挣扎了几个小时,不得不说我很沮丧,也很惊讶触发('click')这样的简单函数会导致这么多问题。
简而言之,我的代码有一个 b 按钮,@click 从 vuex 触发 fetchData 函数。这在浏览器中运行良好,但在测试模式下,fetchData 不会被执行。
Vue 组件代码
<template>
<b-button id="loadButton" variant="outline-primary" @click="fetchData">Load Data</b-button>
</template>
<script>
import { mapActions } from 'vuex';
export default {
name: "LoadAndSave",
methods: { ...mapActions(['fetchData']) }
}
</script>
测试代码
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { BootstrapVue } from 'bootstrap-vue'
import LoadAndSave from '../../resources/components/LoadAndSave'
const localVue = createLocalVue()
localVue.use(BootstrapVue)
localVue.use(Vuex)
describe('LoadAndSave.vue', () => {
let actions
let getters
let store
beforeEach(() => {
actions = {
fetchData: jest.fn()
}
store = new Vuex.Store({
actions
})
})
it('LoadAndSave: onClick executes fetchData', async () => {
const wrapper = shallowMount(LoadAndSave, { localVue, store })
const button = wrapper.find("#loadButton")
await button.trigger('click')
expect(actions.fetchData).toHaveBeenCalled()
})
})
测试结果
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
这不是我第一天编码,我也远不是编码专家,但只是无法点击按钮触发的想法真的让我脊背发凉,更不用说伴随的挫败感.
如果有人可以提出任何建议,将不胜感激。
小程
【问题讨论】:
标签: vue.js jestjs vue-test-utils