我已经在VueJS中编写了一个独立的可重用组件,该组件本质上只是一个输入字段的包装器,但是它会根据传递给它的道具进行键盘输入的智能实时处理。
它的运行就像一种魅力,我能够通过Vue Test Utils(摩卡风味)成功测试其大部分功能,但我也尝试测试其是否正确响应特殊键(箭头,退格键,制表符等)并被卡住。
这是组件本身的编辑后版本:
<template>
<input type="text" v-model="internalValue" :placeholder="placeholder"
@keydown="keyDownHandler"/>
</template>
<script>
export default {
name: "LimitedTextArea",
props: {
fieldname: '',
value: { type: String, default: ""},
placeholder: 'placeholder',
...
},
data: function() {
return {
internalValue: ''
}
},
watch: {
internalValue(newVal /*, oldVal*/ ) {
this.$emit("input", this.fieldname, newVal);
}
},
mounted: function() {
...
},
methods: {
keyDownHandler(evt) {
this.internalValue = this.value;
if (!evt.metaKey && evt.keyCode >= 45) {
evt.preventDefault();
const inputChar = evt.key;
let newChar = '';
/* filtering logic here */
this.internalValue += newChar;
} else {
// just for tracing this path during dev
console.log('will execute default action');
}
}
}
}
</script>
…这是测试:
it('embedded: delete key functions normally', () => {
const initialValue = '';
const inputValue = 'omega';
const outputValue = 'omeg';
const deleteKeyEvent = {key: 'Backspace', keyCode: 8};
const parent = mount({
data: function() { return {
textValue: initialValue
}},
template: \`<div>
<limited-text-area :fieldname="'textValue'" :value="textValue"
@input="input"></limited-text-area>
</div>`,
components: { 'limited-text-area': LimitedTextArea },
methods: {
input(fieldname, value) {
this[fieldname] = value;
}
}
});
const input = parent.find('input');
typeStringIntoField(inputValue, input);
// I've tried with and without this before sending the key event…
input.element.focus();
input.element.setSelectionRange(inputValue.length, inputValue.length);
// I've tried doing it this way
input.trigger('keydown', deleteKeyEvent);
// And I've tried doing it this way, based on the Vue Test Utils guide
// for keyboard events
input.trigger('keydown.up.backspace');
expect(parent.vm.textValue).to.equal(outputValue);
});
以上引用的两种方法均无效。在这一点上,我怀疑调用错误的方法可能不是一个简单的问题,或者我是:
任何帮助将不胜感激!谢谢。