Vue Test Utils 中的“存根子组件”是什么?

2024-04-21

Vue 测试工具 https://vue-test-utils.vuejs.org有一个名为的 API 方法shallowMount() https://vue-test-utils.vuejs.org/api/#shallowmount that:

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

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

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

存根子组件到底是什么?

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

想象一下你有一个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生命周期方法。

如果你打电话html on the ParentComponent包装器,您将看到以下输出:

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
  }
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue Test Utils 中的“存根子组件”是什么? 的相关文章

随机推荐