【发布时间】:2020-06-17 21:00:18
【问题描述】:
这个问题让我很难受,我不明白如何让 Vue Test Utils 和 BootstrapVue 一起玩得很好。
一个最小的例子如下所示:
MyComponent.vue
<template>
<div>
<b-button variant="primary" @click="play">PLAY</b-button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
methods: {
play() {
console.log("Let's play!");
}
}
}
</script>
在main.js 中,我们使用BootstrapVue:Vue.use(BootstrapVue)。
这就是我尝试测试click 事件是否已被触发的方式:
import { expect } from 'chai';
import sinon from 'sinon';
import Vue from 'vue';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import BootstrapVue, { BButton } from 'bootstrap-vue';
import MyComponent from '@/components/MyComponent.vue';
const localVue = createLocalVue();
localVue.use(BootstrapVue);
describe('MyComponent.vue', () => {
it('should call the method play when button is clicked', () => {
const playSpy = sinon.spy();
const wrapper = shallowMount(MyComponent, {
localVue,
methods: {
play: playSpy,
},
});
wrapper.find(BButton).trigger('click');
expect(playSpy.called).to.equal(true);
});
});
这给了我:
AssertionError: expected false to equal true + expected - actual -false +true
我检查了How to test for the existance of a bootstrap vue component in unit tests with jest?,但它不适用于BButton。
运行测试时,我在命令行上也看不到任何输出,我希望这行会被执行:
console.log("Let's play!");
这里有什么问题?
【问题讨论】:
-
要让你的 console.log 运行,你可以试试这个:wrapper.vm.play()
-
@lucas 谢谢,但我的目标不是通过显式调用该方法来让
console.log运行。我想测试触发click事件是否会调用该方法。 -
知道了。但它有效吗?另一种选择是尝试将其更改为 wrapper.find('b-button').trigger('click')
-
@lucas 不,
wrapper.find('b-button')不起作用。wrapper.find('button')也不会。使用 BoostrapVue 时,您必须将组件名称传递给wrapper的find方法。我不知道如何进一步进行以触发事件。 -
我对 BootstrapVue 不熟悉,但我有一个想法可能会对您有所帮助。检查他们如何测试存储库上的按钮。希望它能给你一些见解。 github.com/bootstrap-vue/bootstrap-vue/blob/dev/src/components/…
标签: javascript vue.js dom bootstrap-vue vue-test-utils