代码之家  ›  专栏  ›  技术社区  ›  urig

Vue测试实用程序中的“存根子组件”是什么?

  •  3
  • urig  · 技术社区  · 7 年前

    Vue Test Utils shallowMount() 那就是:

    Wrapper 包含已装载和呈现的Vue组件,但具有存根子组件的。

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

    1. 这些存根子组件到底是什么?
    2. 有没有办法预先规划他们的行为?
    2 回复  |  直到 7 年前
        1
  •  24
  •   Edward Sam    7 年前

    存根子组件到底是什么?

    想象你有一个 ParentComponent 呈现 ChildComponent

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

    子组件 呈现全局注册的组件,并在装入时调用注入的实例方法:

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

    如果你使用 shallowMount 父组件 子组件 子组件 子组件 模板,但它没有 mounted 生命周期方法。

    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
  •  2
  •   Stephan-v    7 年前

    您可以在这个非官方的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测试Utils缺乏相当多的上下文。