Testing with `Created` hook with `vue-test-utils` and `jest`
Because your method is called on created
, it is run before you are setting the mock. Therefore, your test will fail.
You have to replace the method with the mock on initialization (in your case, on shallowMount
):
describe('Xyz', () => { it('should call doSomething() when created', () => { const doSomething = jest.fn() wrapper = shallowMount(Xyz, { localvue, methods: { doSomething } }); expect(doSomething).toHaveBeenCalled(); });});
Sidenote: you're not declaring cmp
. At the start of your test, you should have a let cmp;
A very similar discussion here. Above the linked comment there's a method to mock properties of most Vue component lifecycle hooks.
The methods
option was deprecated in v1 of @vue/test-utils
, so the accepted answer no longer works. I ran into this issue myself and decided to dig into the source to figure out how I could test this.
It looks like Vue actually stores all the hooks in the $options
property. Each hook has an option that is an array of functions. It is important to note that a context is not bound to said functions, so you will need to use call
or apply
to execute them.
vm.$options.created.forEach(hook => { hook.call(vm);});
It's possible to call hooks when we need in our tests. For example if we need to mock some data before calling a hook.
import App from '@/App.vue';// in testApp.created.call(wrapper.vm);
Also in Typescript if we use vue-property-decorator it changes the shape of component, so needs to be done like this:
App.extendOptions.created.call(wrapper.vm)