0

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.

1

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I have moved the this.$store.dispatch('download_todo') in the init function inside methdos, then I mocked this method.
1

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.