uri*_*rig 7 unit-testing stub vue.js vuejs2 vue-test-utils
Vue Test Utils有一个API方法,称为shallowMount():
...创建一个
Wrapper包含已安装和渲染的Vue组件,但包含已存根的子组件.
我搜索了Vue Test Utils文档网站,但未能找到这些存根子组件如何表现的良好解释.
Edd*_*Edd 13
顽固的子组件究竟是什么?
stubbed子组件是被测组件呈现的子组件的替代品.
想象一下,你有一个ParentComponent组件呈现ChildComponent:
const ParentComponent = {
template: `
<div>
<button />
<child-component />
</div>
`,
components: {
ChildComponent
}
}
Run Code Online (Sandbox Code Playgroud)
ChildComponent 呈现全局注册的组件,并在安装时调用注入的实例方法:
const ChildComponent = {
template: `<span><another-component /></span>`,
mounted() {
this.$injectedMethod()
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用shallowMount安装ParentComponent,Vue Test Utils将渲染一个ChildComponent替代原始的存根ChildComponent.存根组件不呈现ChildComponent模板,并且它没有mounted生命周期方法.
如果你调用html了ParentComponent包装器,你会看到以下输出:
const wrapper = shallowMount(ParentComponent)
wrapper.html() // <div><button /><child-component-stub /></div>
Run Code Online (Sandbox Code Playgroud)
存根看起来有点像这样:
const Stub = {
props: originalComonent.props,
render(h) {
return h(tagName, this.$options._renderChildren)
}
}
Run Code Online (Sandbox Code Playgroud)
由于存根组件是使用原始组件中的信息创建的,因此您可以将原始组件用作选择器:
const wrapper = shallowMount(ParentComponent)
wrapper.find(ChildComponent).props()
Run Code Online (Sandbox Code Playgroud)
Vue没有意识到它正在渲染一个存根组件.Vue Test Utils设置它,以便当Vue尝试解析组件时,它将使用存根组件而不是原始组件解析.
他们经历了Vue组件生命周期的哪些部分?
存根遍历Vue生命周期的所有部分.
有没有办法预先编程他们的行为?
是的,您可以创建自定义存根并使用stubs安装选项传递它:
const MyStub = {
template: '<div />',
methods: {
someMethod() {}
}
}
mount(TestComponent, {
stubs: {
'my-stub': MyStub
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2904 次 |
| 最近记录: |