0
votes

So following the setMethods being deprecated in Vue-test-utils, I'm changing my tests to use jest.spyOn. I simply want to emit an event from a child component and check the corresponding method was called on the parent, but somehow my method never gets called.

it('calls promptPasswordReset method when forgotten-password event is emitted from LoginForm', () => {
    const wrapper = shallowMount(login, { store, localVue })
    const promptPasswordResetSpy = jest.spyOn(wrapper.vm, 'promptPasswordReset')
    wrapper.findComponent(LoginForm).vm.$emit('forgotten-password')
    expect(promptPasswordResetSpy).toHaveBeenCalled()
})

The corresponding child template:

<login-form
    @login="login"
    @sign-up="isSignUpModalActive = true"
    @forgotten-password="promptPasswordReset"
>
</login-form>

I don't understand because the event is properly emitted when I check wrapper.emitted and spyOn works because if I manually trigger the method, it is called!

1

1 Answers

2
votes

To spy on a component's methods, use jest.spyOn() on the component's methods definition, and then mount:

import MyComponent from '@/components/MyComponent.vue'

//...                                                   👇
const promptPasswordResetSpy = jest.spyOn(MyComponent.methods, 'promptPasswordReset')
const wrapper = shallowMount(MyComponent, /*...*/)
wrapper.findComponent(LoginForm).vm.$emit('forgotten-password')
expect(promptPasswordResetSpy).toHaveBeenCalled()