我正在尝试使用 AVA 和 Avoriaz 测试 Vue.js 组件的计算属性。我可以挂载组件并正常访问数据属性。
当我尝试访问计算属性时,该函数似乎对该组件上的数据没有作用域。
computed: {
canAdd() {
return this.crew.firstName !== '' && this.crew.lastName !== '';
}
我得到的错误是Error: Cannot read property 'firstName' of undefined
测试文件:
import Vue from 'vue';
import { mount }
from 'avoriaz';
import test from 'ava';
import nextTick from 'p-immediate';
import ComputedPropTest from '../../../js/vue-components/computed_prop_test.vue';
Vue.config.productionTip = false;
test.only('Should handle computed properties', async(t) => {
const MOCK_PROPS_DATA = {
propsData: {
forwardTo: '/crew',
crew: {}
}
},
wrapper = mount(ComputedPropTest, MOCK_PROPS_DATA),
DATA = {
crew: {
firstName: 'Ryan',
lastName: 'Gill'
}
};
wrapper.setData(DATA);
await nextTick();
console.log('firstName: ', wrapper.data().crew.firstName); // Ryan
console.log('isTrue: ', wrapper.computed().isTrue()); // true
console.log('canAdd: ', wrapper.computed().canAdd()); // Errors
t.true(wrapper.computed().isTrue());
});
零件:
<template>
<div>
<label for="firstName" class="usa-color-text-primary">First Name
<i class="tooltipTextIcon fa fa-info-circle usa-color-text-gray" title="First name of crew."></i>
<span class="required usa-additional_text usa-color-text-secondary-dark">Required</span>
</label>
<input id="firstName" type="text" class="requiredInput" name="firstName" v-model="crew.firstName" autofocus>
<label for="lastName" class="usa-color-text-primary">Last Name
<i class="tooltipTextIcon fa fa-info-circle usa-color-text-gray" title="Last name of crew."></i>
<span class="required usa-additional_text usa-color-text-secondary-dark">Required</span>
</label>
<input id="lastName" type="text" class="requiredInput" name="lastName" v-model="crew.lastName" autofocus>
</div>
</template>
<script>
export default {
name: 'crew-inputs',
data() {
return {
crew: {
firstName: '',
lastName: ''
}
}
},
computed: {
canAdd() {
return this.crew.firstName !== '' && this.crew.lastName !== '';
},
isTrue() {
return true;
}
}
}
</script>
计算isTrue
属性似乎可以工作,但不依赖于组件中的任何数据。