【问题标题】:Async lifecycle function in Vue Test UtilsVue Test Utils 中的异步生命周期函数
【发布时间】: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


【解决方案1】:

shallowMount 没有返回Promise,这就是为什么没有什么可以等待的原因。要在测试中等待承诺,请尝试使用 flush-promises 库。使用flushPromises,您的测试将如下所示:

import flushPromises from 'flush-promises'

wrapper = shallowMount(Component, {
      localVue
    });
await flushPromises(); // we wait until all promises in created() hook are resolved
// expect...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 2017-07-06
    • 2018-10-21
    • 2020-04-06
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多