1

我在组件的 v-model 中测试调度操作时遇到问题。我有一个多选,每次值更改时都会触发调度操作,因为所选值存储在 na Vuex 存储中。我想测试在多选中选择一个值后是否调用了调度操作。

<multiselect
      v-model="subdivision"
      :options="options"
      :multiple="false"
      :close-on-select="true"
      :clear-on-select="false"
      :preserve-search="false"
      placeholder="Please select"
      label="name"
      track-by="name"
      :preselect-first="false"
      selectedLabel="✓"
      deselectLabel="×"
      selectLabel=" "
      ref="myMultiselect"
      id="multiselectId"
    ></multiselect>

     computed: {
       subdivision: {
         set(value) {
           this.$store.dispatch("subdivision", value);
       },
        get(value) {
           return this.$store.state.subdivision;
       }
     }
    }

那就是测试:

describe('Value change of subdivision', () => {
  let multiselect;
  let cmp2;
  let actions;
  let mutations;
  let state;
  let getters;

  beforeEach(() => {
    actions = {
      subdivision: jest.fn()
    };
    state = storeConfig.state;
    mutations = storeConfig.mutations;
    getters = storeConfig.getters;
    store = new Vuex.Store({ state, getters, mutations, actions });

    cmp2 = shallowMount(MyComponent, {
      store,
      localVue,
      router
    });
  })

  it('Select value should dispatch action', () => {
    let multiselect = cmp2.find({ ref: 'myMultiselect' });
    multiselect.trigger('input',subdivisions[1]);
    expect(actions.subdivision).toHaveBeenCalled();
  })
})

它不工作。我收到以下错误。

expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.

怎么了?请帮忙。

4

1 回答 1

1

问题是输入事件没有被触发。输入事件是一个组件自定义事件,这就是触发器不起作用的原因。

multiselect.trigger('input',subdivisions[1]);  // <-- wrong

使用 v-model 在 vue-multiselect 上触发事件的正确方法如下:

multiselect = wrapper.find({ ref: 'myMultiselect' });
let obj = { value: 12122, name: 'Hans Peter' };
multiselect.vm.$emit('input', obj );
于 2019-11-04T12:38:18.967 回答