测试 v-model
在编写依赖于 v-model 交互(update:modelValue 事件)的组件时,您需要处理 event 和 props。
查看 "vmodel 集成" 讨论 以获取一些社区解决方案。
一个简单的例子
这里有一个简单的编辑器组件
js
const Editor = {
props: {
label: String,
modelValue: String
},
emits: ['update:modelValue'],
template: `<div>
<label>{{label}}</label>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</div>`
}此组件将仅作为输入组件。
js
const App = {
components: {
Editor
},
template: `<editor v-model="text" label="test" />`,
data(){
return {
text: 'test'
}
}
}现在,当我们在输入框中键入时,它将更新我们组件上的 text。
要测试此行为
js
test('modelValue should be updated', async () => {
const wrapper = mount(Editor, {
props: {
modelValue: 'initialText',
'onUpdate:modelValue': (e) => wrapper.setProps({ modelValue: e })
}
})
await wrapper.find('input').setValue('test')
expect(wrapper.props('modelValue')).toBe('test')
})多个 v-model
在某些情况下,我们可以有多个 v-model 针对特定属性。
例如,一个货币编辑器,我们可以有 currency 和 modelValue 属性。
js
const MoneyEditor = {
template: `<div>
<input :value="currency" @input="$emit('update:currency', $event.target.value)"/>
<input :value="modelValue" type="number" @input="$emit('update:modelValue', $event.target.value)"/>
</div>`,
props: ['currency', 'modelValue'],
emits: ['update:currency', 'update:modelValue']
}我们可以通过以下方式测试两者
js
test('modelValue and currency should be updated', async () => {
const wrapper = mount(MoneyEditor, {
props: {
modelValue: 'initialText',
'onUpdate:modelValue': (e) => wrapper.setProps({ modelValue: e }),
currency: '$',
'onUpdate:currency': (e) => wrapper.setProps({ currency: e })
}
})
const [currencyInput, modelValueInput] = wrapper.findAll('input')
await modelValueInput.setValue('test')
await currencyInput.setValue('£')
expect(wrapper.props('modelValue')).toBe('test')
expect(wrapper.props('currency')).toBe('£')
})