我是Jest的新手,正在尝试为我的Vue应用程序编写一个测试,该测试将确认子组件是否会发出事件,结果是,它的prop值会更新。
作为一个例子,我制作了一个简单的应用程序,其中包含一个计数器来演示:
/* Parent Home.vue */
<template>
<Counter :count="count" @increment="count++"/>
</template>
<script>
import Counter from "@/components/Counter.vue";
export default {
components: { Counter },
data: () => ({
count: 0,
}),
};
</script>/* Child Counter.vue */
<template>
<v-container>
<div id="propTracker">{{ count }}</div>
<v-btn ref="incrementProp" @click="increment($event)">Increase prop</v-btn>
</v-container>
</template>
<script>
export default {
props: ["count"],
methods: {
increment() {
this.$emit("increment");
},
},
};
</script>一旦Counter中的按钮被按下,它就应该发出一个increment事件来递增父Home组件中的计数。
这是我写的测试:
it("Click should increment count text", async () => {
const wrapper = mount(Counter, {
localVue,
vuetify,
propsData: { count: 0 },
});
expect(wrapper.find("#propTracker").text()).toBe("0"); //initial state
const button = wrapper.find({ ref: "incrementProp" });
await button.trigger("click"); //trigger click
expect(wrapper.find("#propTracker").text()).toBe("1"); //after click
});它以Expected: "1" Received: "0"的形式返回,表明正确的更新不会在测试中处理。我尝试组合了许多资源,比如Vue guidelines here和Vuetify单元测试信息here,但它总是返回相同的内容。我丢了一块拼图,已经找了两天了。
这是一个简化的repo,可以获得更好的图片,也可以在本地播放。
有一个测试用来测试递增是否适用于本地数据值:here,所以这就是目前让我抓狂的道具和发射的场景。任何帮助都是有价值的!
发布于 2020-11-09 00:55:57
好了,我终于找到解决方案了!我走错了路,试图在一个子组件中测试父数据的变化。使用我的组合(子组件计数器发出事件并触发主主组件中的更改),这是工作测试:
it("Counter button changes count in Home", () => {
const wrapper = mountFactory(Home);
//check if initial count in Home is 0
expect(wrapper.vm.count).toBe(0);
//click btn in Counter (child component)
wrapper.find("#incrementBtn").trigger("click");
//check if increment worked and count has increased
expect(wrapper.vm.count).toBe(1);
});学习曲线来思考"Jest“:)
发布于 2020-11-05 23:29:00
我下载了您的存储库并进行了测试,一切工作正常。除了标题没有定义变量之外。请参阅打印:https://puu.sh/GKmzu/69a9fe9f0a.png
发布于 2020-11-08 07:16:44
我认为你应该测试事件是否被触发。请注意,如果您测试本地计数器,则测试将通过,但不会通过属性计数。这是因为测试看不到Home组件上的代码。请记住,这是一个单元测试,目标是隔离测试组件。
https://stackoverflow.com/questions/64699982
复制相似问题