Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Triggering a submit event not updating call count in Jest + Vue Test Utils

In Vue 2.6.12 with Jest: "^27.5.1" and "@vue/test-utils": "^1.3.0", I am trying to mock out an async method using jest. When I assert that my method has been called 1 time, it returns that it has not been called. Am I doing something blatantly wrong?

Update Email Test

    import {mount} from '@vue/test-utils';
    import UpdateEmail from './components/update-email.vue';

    //validate form method testing
    test('should submit form', async () => {
        let wrapper = mount(UpdateEmail);
        const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail');
        // //Get our form fields
        await wrapper.find('#email').setValue('johndoe@test.com')
        await wrapper.find('#password').setValue('MyPassword');
        await wrapper.find('form').trigger('submit.prevent');

        expect(mockedFormSubmit).toHaveBeenCalledTimes(1);
    });

UpdateEmail Method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    async updateEmail() {
      this.validateFields();

        try {
           await axios.post(this.updateEmailPath, {
            password: this.password,
            email: this.email
          });
        } catch (e) {
          console.log(e.message);
        }
    },

Output in console when test runs:

 expect(jest.fn()).toHaveBeenCalledTimes(expected)

    Expected number of calls: 1
    Received number of calls: 0

      35 |         await wrapper.find('form').trigger('submit.prevent');
      36 |
    > 37 |         expect(mockedFormSubmit).toHaveBeenCalledTimes(1);
         |                                  ^
      38 |     });
      39 | });

>Solution :

The method must be mocked before mounting the component:

test('should submit form', async () => {

  const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ✅
  let wrapper = mount(UpdateEmail);
  // const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ❌

  ⋮
});

demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading