Search code examples
vue.jsjestjsvuexvue-test-utilsvue-multiselect

Jest expected mock function to have been called on testing vuex actions in vue-multiselect


i have problems to test a dispatch action in v-model of component. I have a multiselect and every time when a values changes a dispatch action is fired, because the selected value is stored in na Vuex store. I want to test that dispatch action has been called after a value has been selected in multiselect.

<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;
       }
     }
    }

Thats the test:

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();
  })
})

Its not working. I get the following error.

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

What is wrong? Please help.


Solution

  • The problem was that the input event was not triggered. The input Event is a component custom event thats why trigger doesnt work.

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

    The right way to trigger an event on vue-multiselect by using v-model is the following:

    multiselect = wrapper.find({ ref: 'myMultiselect' });
    let obj = { value: 12122, name: 'Hans Peter' };
    multiselect.vm.$emit('input', obj );