【问题标题】:What are "stubbed child components" in Vue Test Utils?Vue Test Utils 中的“存根子组件”是什么?
【发布时间】:2019-03-28 11:38:22
【问题描述】:

Vue Test Utils 有一个名为 shallowMount() 的 API 方法:

...创建一个 Wrapper,其中包含已安装和渲染的 Vue 组件,但带有存根的子组件。

我搜索了 Vue Test Utils 文档网站,但未能很好地解释这些存根子组件的行为方式。

  1. 这些存根子组件到底是什么?
  2. 他们经历了 Vue 组件生命周期的哪些部分?
  3. 有没有办法对他们的行为进行预编程?

【问题讨论】:

  • 也许这可以帮助您在搜索vue stubbed components 时在第一页的第一个结果中提供帮助。 lmiller1990.github.io/vue-testing-handbook/…
  • @Stephan-v 谢谢。我不知道我是怎么错过的。非常欢迎您在此处的答案中发布链接 + 答案,我很乐意接受。 + 我还没有找到的一件事是如何使用所需的测试行为对存根进行预编程。

标签: unit-testing vue.js vuejs2 stub vue-test-utils


【解决方案1】:

什么是存根子组件?

存根子组件是被测试组件呈现的子组件的替代品。

假设您有一个 ParentComponent 组件,它呈现一个 ChildComponent

const ParentComponent = {
  template: `
    <div>
      <button />
      <child-component />
    </div>
  `,
  components: {
    ChildComponent
  }
}

ChildComponent 渲染一个全局注册的组件,并在挂载时调用注入的实例方法:

const ChildComponent = {
  template: `<span><another-component /></span>`,
  mounted() {
    this.$injectedMethod()
  }
}

如果您使用shallowMount 挂载ParentComponent,Vue Test Utils 将呈现一个ChildComponent 的存根,而不是原始的ChildComponent。存根组件不渲染ChildComponent模板,也没有mounted生命周期方法。

如果您在 ParentComponent 包装器上调用 html,您将看到以下输出:

const wrapper = shallowMount(ParentComponent)
wrapper.html() // <div><button /><child-component-stub /></div>

存根看起来有点像这样:

const Stub = {
  props: originalComonent.props,
  render(h) {
    return h(tagName, this.$options._renderChildren)
  }
}

由于存根组件是使用原始组件的信息创建的,因此您可以将原始组件用作选择器:

const wrapper = shallowMount(ParentComponent)
wrapper.find(ChildComponent).props()

Vue 不知道它正在渲染一个存根组件。 Vue Test Utils 设置它,以便当 Vue 尝试解析组件时,它将使用存根组件而不是原始组件进行解析。

它们经历了 Vue 组件生命周期的哪些部分?

存根贯穿 Vue 生命周期的所有部分。

有没有办法对他们的行为进行预编程?

是的,您可以创建一个自定义存根并使用 stubs 安装选项传递它:

const MyStub = {
  template: '<div />',
  methods: {
    someMethod() {}
  }
}

mount(TestComponent, {
  stubs: {
    'my-stub': MyStub
  }
})

【讨论】:

    【解决方案2】:

    您可以在这个非官方的 Vue 测试指南中找到关于存根组件的更多信息。

    https://lmiller1990.github.io/vue-testing-handbook/#what-is-this-guide

    简而言之:

    存根只是代表另一个的一段代码。

    Vue Test Utils 信息中也有一些关于shallow mount 的信息:

    https://vue-test-utils.vuejs.org/guides/#common-tips

    不过,Vue 测试工具缺乏相当多的上下文。

    【讨论】:

    • 谢谢。我还提到该指南描述了在存根中“内部方法,例如 makeApiCall,被不做任何事情的虚拟方法取代”。最重要的是 - 关于如何在安排测试时将这些内部方法预编程为所需行为的任​​何想法?
    猜你喜欢
    • 2021-09-19
    • 2019-04-26
    • 1970-01-01
    • 2019-07-16
    • 2019-11-14
    • 1970-01-01
    • 2021-02-17
    • 2019-11-19
    • 2019-09-10
    相关资源
    最近更新 更多