【发布时间】:2021-06-12 21:31:43
【问题描述】:
当我尝试测试具有这样挂载方法的组件时:
mounted(){
this.search()
}
methods:{
async search(){
try{
await axios.something
console.log("not executed only when shallowMount")
}catch{}
}
}
我检查了它返回了 Promise
我这样写测试:
wrapper = await shallowMount(Component, {
localVue
});
await wrapper.vm.search()// this works perfectly
但是,只有 shallowMount 显然会跳过等待的功能,而下一行可以完美运行。
我不知道这种行为。
我该如何解决?
编辑:
我还使用 Mirage.js 来模拟响应。
function deviceServer() {
return createServer({
environment: "test",
serializers: {
device: deviceListSerializer()
},
models: {
device: Model
},
fixtures: {
devices: devices
},
routes() {
this.namespace = "/api/v1/";
this.resource("device");
},
seeds(server) {
server.loadFixtures("devices");
}
});
}
【问题讨论】:
-
你能提供一些可重现的例子吗?如果你想打电话给
search,为什么还需要shallowMount? -
因为这个组件是一个容器组件,有两个子组件(搜索框、表格)。该组件只处理数据(由 API 提供)。
-
面对同样的问题,我想使用 async/await 从 created() 或 mount() 钩子中获取 API 数据。对我来说, shallowMount 似乎不是异步函数,所以 await 在那里不起作用。目前,我使用 setTimeout 的丑陋解决方法,等待几秒钟,在传递来自 API 的数据之后,甚至同步调用 mount() 或 created() 钩子。相当可怕。我真的很感兴趣有什么更好的方法来做到这一点。
标签: vue.js async-await promise vue-cli vue-test-utils