sam
sam

Reputation: 21

how to mock 'mounted' method of VueJs component?

Thanks for you help in advance.

How is the mounted() method mocked for testing?

The Component is like this:

export default {
    
    name: 'ShowToDo',
    ...
    mounted(){
        this.$store.dispatch('download_todo')
    },
    ...
}

Instead, the Component-test is:

  const localVue = createLocalVue()
        localVue.use(Vuex)
        wrapper = mount(ShowToDo, {
            store,
            localVue,
            mounted(){}
            }
        )
    })

It seems that mounted(){} is ignored, because the test try to execute this.$store.dispatch('download_todo') .

Thanks in advance.

Upvotes: 0

Views: 2208

Answers (2)

Eduardo
Eduardo

Reputation: 1321

You can't assert that lifecycle hook was called but you can assert the $store.dispatch was called. I suggest you to not use real Vuex store at all. One of the best practices is to test the store separately mocking the $store object in components. With mock $store you can not just check that the action was dispatched but also check what arguments it was dispatched with:


const wrapper = mount(ShowToDo, {
   mocks: {
     $store: {
       dispatch: jest.fn()
     }
   },
})
expect(wrapper.vm.$store.dispatch).toHaveBeenCalledWith('download_todo')

Upvotes: 1

Kapcash
Kapcash

Reputation: 6909

Sorry, but you can't mock Vue lifecycle hooks.

Source: vue-test-utils issue #166

What you can do though it mocking your store. Instead of using your real store, you can provide one with a custom download_todo declared action.

So the mounted hook will be run and dispatch the download_todo action, but it will be a custom one :)

import { state, mutations, getters, actions } from '../store'

const downloadActionMock = jest.fn()
const store = new Vuex.Store({
  state,
  mutations,
  getters,
  actions: {
    ...actions, // Use the real actions
    download_todo: downloadActionMock // Override some of them
  }
})

wrapper = mount(ShowToDo, {
    store,
    localVue,
  }
)

expect(downloadActionMock).toHaveBeenCalled()

Upvotes: 1

Related Questions