En Vue 2.6.12 con Jest: "^27.5.1" y "@vue/test-utils": "^1.3.0", intento simular un método async usando jest. Cuando afirmo que mi método ha sido llamado 1 vez, devuelve que no ha sido llamado. ¿Estoy haciendo algo descaradamente mal?
Actualizar prueba de correo electrónico
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); });Actualizar método de correo electrónico
async updateEmail() { this.validateFields(); try { await axios.post(this.updateEmailPath, { password: this.password, email: this.email }); } catch (e) { console.log(e.message); } },Salida en la consola cuando se ejecuta la prueba:
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 | });Para Vue 2, se debe simular el método antes de montar el componente porque los .methods del componente se conectan solo durante el montaje:
test('should submit form', async () => { const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ✅ let wrapper = mount(UpdateEmail); // const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ❌ ⋮ }); En Vue 3, los métodos se pueden simular después del montaje directamente desde wrapper.vm (a partir de Vue 3.2.31).