1

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 Answer 1

5

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

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.