dul*_*ong 3 vue.js jestjs vue-test-utils
已经阅读了很多 stackoverflow 和 github 讨论,关于 vue jest 在使用 button.trigger('click') 时遇到问题。今天我一直在为这个问题苦苦挣扎了几个小时,不得不说我很沮丧,并且很惊讶一个简单的函数,比如 trigger('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>
Run Code Online (Sandbox Code Playgroud)
测试代码
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()
})
})
Run Code Online (Sandbox Code Playgroud)
测试结果
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
Run Code Online (Sandbox Code Playgroud)
这不是我第一天编码,我也不是编码专家,但只是无法点击按钮来触发的想法真的让我脊背发凉,更不用说随之而来的挫败感了。
如果有人可以提出任何建议,将不胜感激,谢谢。
小程
小智 5
我也一直在为此苦苦挣扎,似乎有时测试组件很难找到对没有括号的函数的发出/调用。
it('Calls save() when pressing save button', async () => {
const savebutton = wrapper.find('#saveButton')
const spy = jest.spyOn(wrapper.vm, 'save')
savebutton.trigger('click')
await wrapper.vm.$nextTick()
expect(spy).toHaveBeenCalled()
jest.restoreAllMocks()
})
Run Code Online (Sandbox Code Playgroud)
上面的测试在这里会失败:
<button class="btn btn-success" id="saveButton" @click="save">Save</button>
Run Code Online (Sandbox Code Playgroud)
但不是在这里:
<button class="btn btn-success" id="saveButton" @click="save()">Spara</button>
Run Code Online (Sandbox Code Playgroud)
您至少可以检查这是否是您的问题,在方法中引用 store 函数并在元素上使用括号调用该函数。
另一种断言按钮点击已被触发的方法是查看发射的对象。
it('Calls save() when pressing save button', () => {
const savebutton = wrapper.find('#saveButton')
savebutton.trigger('click')
expect(wrapper.emitted('save')).toHaveLength(1)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4584 次 |
| 最近记录: |