我正在尝试测试一个组件,该组件应该在用户单击时隐藏。功能在浏览器中工作,但在使用 Jest 进行自动化测试时测试失败。
这是测试:
it(`If the local variable is set to be clicked,
then the tip is hidden`, () => {
const wrapper = mount(Component, { props });
wrapper.setData({ was_clicked: true });
wrapper.vm.$forceUpdate();
expect(wrapper.classes()).toContain("hide"); // fails here
expect(wrapper.find(".toast").isVisible()).toBe(false);
});
这是组件:
<template>
<div @click="hide" class="toast" :class="{ hide: was_clicked }">
...
</div>
</template>
<script>
export default {
name: ...,
data() {
return {
was_clicked: false,
};
},
props: {
...
},
methods: {
hide(event) {
this.was_clicked = true;
},
},
};
</script>
我试图在测试中添加和删除 wrapper.vm.$forceUpdate();
,此外,我还测试了 wrapper.vm 的
nextTick
最佳答案
wrapper.vm.$forceUpdate();
返回一个 promise 。您应该 await
该 promise (并将该函数标记为 async
),或者将其后面的 expect()
移至 .然后
。同样的情况也适用于 vm.$nextTick();
。这是与我一起工作的代码:
it(`If the local variable is set to be clicked, then the tip is hidden`, async () => {
const wrapper = mount(Tip, { props });
wrapper.setData({ was_clicked: true });
await wrapper.vm.$nextTick();
expect(wrapper.classes()).toContain("hide");
expect(wrapper.isVisible()).toBe(false);
});
关于Vue.js 用 Jest 进行测试,类绑定(bind)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61608804/