How do I force input to an input field managed by

2019-08-17 07:09发布

I want to test that a Vue component is properly parsing and saving data after an input field it is watching receives input.

The component looks like this:

<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.

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).

I've tried simply

const input = vm.$el.querySelector('#test'); input.text = 'hello';

but am getting a Attempted to assign to readonly property. error.

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.

1条回答
在下西门庆
2楼-- · 2019-08-17 07:19

This should be what you're looking for:

<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 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.

查看更多
登录 后发表回答