如何将输入强制输入Vue管理的输入字段以进行测试? [英] How do I force input to an input field managed by Vue for testing?
问题描述
我要测试Vue组件正在监视的输入字段接收到输入后是否正确解析并保存了数据.
I want to test that a Vue component is properly parsing and saving data after an input field it is watching receives input.
该组件如下所示:
<template>
<div>
<form>
<div :key="key" v-for="key in contexts" class="row">
<div class="input-field">
<input v-model="saved_contexts[key]" placeholder="" :id="key" type="text">
<label :for="key">{{key}}</label>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return {saved_contexts: {}}
}
},
</script>
我遗漏了填充上下文"数组的代码,请假定它在那里并且可以正常工作.
I have left out the code that fills the "contexts" array, please assume it's there and working.
我想编写一个测试来证明输入字段的输入将导致saved_contexts
对象正确更新(正确的键名已使用正确的值更新).
I want to write a test that demonstrates that input to the input field will caused the saved_contexts
object to be updated properly (that the right key name was updated with the right value).
我只是尝试过
const input = vm.$el.querySelector('#test');
input.text = 'hello';
const input = vm.$el.querySelector('#test');
input.text = 'hello';
,但出现Attempted to assign to readonly property.
错误.
我正在探索调度输入事件,但是我无法弄清楚如何将包含的文本实际放入输入字段中.
I'm exploring dispatching input events, but I can't figure out how to do that with an included text to actual be put in to the input field.
推荐答案
这应该是您想要的:
<template>
<div>
<form>
<div v-for="key in contexts" :key="key" class="row">
<div class="input-field">
<input v-model="saved_contexts[key]"
:id="key"
@change="logInput(key, saved_contexts[key])"
placeholder=""
type="text">
<label>{{key}}</label>
</div>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
contexts: [
'one',
'two',
'three',
],
saved_contexts: {},
};
},
methods: {
logInput(key, input) {
console.log(`saved_contexts's key: '${key}', updated with input: '${input}'`);
console.log(this.saved_contexts[key] === input);
console.log(this.saved_contexts);
},
},
};
</script>
Vue在直接操作DOM时会遇到一些问题,但是这里有一个日志记录功能,该功能可以验证输入是否已保存到save_contexts.
Vue has some issues when manipulating the DOM directly, but here you have a logging function, which verifies that the input has been saved to the saved_contexts.
这篇关于如何将输入强制输入Vue管理的输入字段以进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!