【发布时间】:2020-02-27 07:05:55
【问题描述】:
我正在为我在 Vue 中构建的组件构建一个开玩笑的测试环境。该组件期望一个由该组件父级上的 vue 插件计算的对象作为道具。 (特别是由 vuelidate 插件计算的 $v 对象)
我的测试方法是使用 vue-test-utils 的 shallowMount 的 options 参数的 parentComponent 和 propsData 属性,但我不知道如何将变量从父级传递给组件的 props。
TextField.spec.js:
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuelidate from 'vuelidate';
import FormField from '../../../../src/components/fields/FormField.vue';
const localVue = createLocalVue();
localVue.use(Vuelidate);
localVue.component('form-field', FormField);
parent = {
data() {
return {
value: 4,
};
},
//this property is consumed by Vuelidate, which creates an object on localVue
validations: {
value: {
required,
},
},
};
wrapper = shallowMount(FormField, {
localVue,
parentComponent: parent,
propsData: {
label: 'test label',
validatorField: $v.value,
},
});
TextField.vue
<template>
<label>
{{label}}
{{required? '*' : ''}}
</label>
</template>
<script>
export default {
props: {
label: String,
validatorField: Object,
},
computed: {
required() {
return Object.keys(this.validatorField).includes('required');
}
},
};
</script>
上述代码的预期结果是FormField 组件接收从父级创建的validatorField 属性,但是在我调用它的上下文中没有定义$v。我也尝试用":validatorField": "$v.value" 替换validatorField: $v.value 并传入一个函数,但没有成功。有什么方法可以正确传递这个道具吗?也许通过检索对 parentComponent 的引用?
【问题讨论】:
标签: vue.js vue-test-utils