Vue Test Utils 中的 "stubbed child components" 是什么?

What are "stubbed child components" in Vue Test Utils?

Vue Test Utils has an API method called shallowMount() 即:

...creates a Wrapper that contains the mounted and rendered Vue component, but with stubbed child components.

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

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

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

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

简而言之:

A stub is simply a piece of code that stands in for another.

Vue Test Utils资料也有一些关于shallow mount的资料:

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

Vue Test Utils 缺少相当多的上下文。

存根子组件到底是什么?

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

假设您有一个呈现 ChildComponent:

ParentComponent 组件
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
  }
})