什么是存根子组件?
存根子组件是被测试组件呈现的子组件的替代品。
假设您有一个 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
}
})