was_777
was_777

Reputation: 711

Can we modify Vuex action for jest unit testing?

I've created a store in my test file

import {
shallowMount,
createLocalVue
} from '@vue/test-utils'
import Vuex from 'vuex'
import Actions from '../../../src/components/Actions'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Actions.vue', () => {
  let actions
  let store

beforeEach(() => {
    actions = {
        actionClick: jest.fn(() => Promise.resolve({}))
    }
    store = new Vuex.Store({
        actions
    })
})

it('should go to then block', () => {
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //goes to then block
})

it('should go to catch block', () => {
    actions.actionClick = jest.fn(() => Promise.reject(new Error()))
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //still goes to then block and not the catch block
  })
})

As per the code above the im not able to achieve the second test block means it is not modifying the actionClick function in store.

Upvotes: 1

Views: 1268

Answers (1)

Dima Kuzmich
Dima Kuzmich

Reputation: 1316

The beforeEach hook happens before it goes into the it block. So the store setup is actually completed at this moment. As far as I can see from the vuex source, it detaches the action callbacks from the options object that you've passed to it at the creation step (store = new Vuex.Store(...)). You can check it here.

So, I'd suggest you either creating new store object inside your it block:

it('should go to catch block', () => {
    actions.actionClick = jest.fn(() => Promise.reject(new Error()))
    store = new Vuex.Store({ actions })
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //still goes to then block and not the catch block
  })
})

Or using hotUpdate (newOptions) method on the store instance. I didn't test this one. But, again, from the vuex source it is supposed to do exactly what you need.

it('should go to catch block', () => {
    actions.actionClick = jest.fn(() => Promise.reject(new Error()))
    store.hotUpdate({ actions })
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //still goes to then block and not the catch block
  })
})

Upvotes: 1

Related Questions