[英]Update props in instance of an vue component for unittest
我即将测试 Vue 组件中的一些行为,这些行为仅在道具更改时发生。 Vue 组件看起来和这个组件类似,测试的相关逻辑发生在 watcher 中。
<script>
export default {
components: {
},
props: {
examleProp: {
type: Boolean,
required: false,
default: false,
}
},
watch: {
exampleProp: function(newVal, oldVal) {
// logic which needs to be tested
},
}
};
</script>
<template>
<h1>hello world</h1>
</template>
遵循以下方法时,测试逻辑运行良好。
it('example test', done => {
let wrapper = mount(exampleComponent, {
propsData: {
},
template: `
<example-component >
</example-component>
`
});
wrapper.setProps({
isSubmitting: true
});
});
观察者被调用并准备接受测试,一切都很好。
由于测试应该集成在测试套件中,因此存在一些限制。 该组件未安装,但它的实例如下所示:
it('example test', done => {
let wrapper = new Vue({
components: {
exampleComponent,
},
template: `
<example-component></example-component>
`,
}).$mount();
// how to update props now?
// wrapper.setProps && wrapper.$setProps are both undefined
});
所以我想要实现的是一种更新组件实例的道具以触发观察者运行的方法,对此有什么想法吗?
如果您绝对必须在测试套件中使用实际的 Vue 实例而不是 test-utils 包装器,您可以这样做:
vm.unchanged
)来更新 prop。vm.$set
调用插入到vm.mounted()
生命周期钩子中,该钩子会更改vm.unchanged
,从而触发exampleComponent.exampleProp
上的watch
。 const exampleComponent = { components: { }, template: `<div> <h1 style="color: green">ExamleProp unchanged: {{ exampleProp }}</h1> <h1 style="color: red">Updated: {{ updated }}</h1> </div>`, props: { exampleProp: { type: Boolean, required: false, default: false, } }, data() { return { updated: false, }; }, watch: { exampleProp: function(newVal, oldVal) { this.updated = true; }, } }; const vm = new Vue({ el: '#app', components: { exampleComponent, }, data: { unchanged: true, }, template: ` <example-component:example-prop="unchanged"></example-component> `, mounted() { this.$set(this, 'unchanged', false); } }).$mount();
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"></div>
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.