user11820495
user11820495

Reputation:

How to mock dispatch in vueJs testing

I am currently performing unit tests on my application as seen. But I have a problem. How to mock or exploit the dispatch of Vuex ?

My method to test :

methodA({ dispatch, commit }, { data }) {
        dispatch('methodB', { data });
    }
  };

My unit test :

describe('UnitTesting', () => {
  it('if method called', () => {
    const commit = jest.fn();
    const dispatch = jest.fn('methodB');
    service.actions.methodA({ dispatch, commit });
    expect(dispatch).toHaveBeenCalledTimes(1);
  });

I have a error message : Dispatch is not a function. Why ? Do you help me please ? I don't understand why I had this message.

thanks

Upvotes: 2

Views: 5615

Answers (2)

leonheess
leonheess

Reputation: 21339

In case you additionally want to create a localVue and have the store work normally in your tests you can use spyOn:

const storeDispatch = jest.spyOn(wrapper.vm.$store, 'dispatch')
expect(storeDispatch).toHaveBeenCalledWith('module/action', {})

Upvotes: 2

Renaud
Renaud

Reputation: 1300

jest.fn('methodB') is not not a proper call, thus the resulting dispatch constant not being a function.

The fn parameter should be a function. Either do jest.fn(() => Promise.resolve('functionB')) or jest.fn().mockResolvedValue('functionB')

But just jest.fn() would make it here.

Upvotes: 2

Related Questions