存根子组件到底是什么?
存根子组件是被测试组件呈现的子组件的替代品。
想象一下你有一个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
}
})