【问题标题】:Wait for onMounted() to finish inside test等待 onMounted() 完成内部测试
【发布时间】:2021-12-08 22:49:36
【问题描述】:

在我的设置中,我在 onMounted 函数中执行了几个函数。在我的测试中,我想等待这些完成。我怎样才能做到这一点?

我尝试使用nextTickflushPromises(尽管没有任何承诺),但它们都不起作用。

下面是一些示例代码:

Vue 组件:

setup() {
  const mounted = ref(false);
  onMounted(() => {
    mounted.value = true;
  })
}

测试:

describe('TestComponent', () => {
  const wrapper = shallowMount(TestComponent)
  it('expects mounted to be true after mount', () => {
    expect(wrapper.vm.mounted).toBe(true)
  })
})

【问题讨论】:

  • 你得到的错误是什么?
  • 我没有收到错误。测试失败,因为运行测试时“已安装”变量仍然为假
  • 如果测试失败,说明有错误。请列出来。

标签: vue.js jestjs vuejs3 vue-composition-api


【解决方案1】:

缺少的是在设置组件后导出数据:

setup() {
  const mounted = ref(false);
  onMounted(() => {
    mounted.value = true;
  })

  return { mounted };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-15
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2019-02-10
    • 2023-01-28
    • 2018-03-30
    相关资源
    最近更新 更多