In Vue 2.6.12with Jest:我正在嘗試使用 jest 模擬一個"^27.5.1"方法。當我斷言我的方法已被呼叫 1 次時,它回傳它尚未被呼叫。我在做一些公然錯誤的事情嗎?"@vue/test-utils": "^1.3.0",async
更新電子郵件測驗
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('[email protected]')
await wrapper.find('#password').setValue('MyPassword');
await wrapper.find('form').trigger('submit.prevent');
expect(mockedFormSubmit).toHaveBeenCalledTimes(1);
});
更新電子郵件方法
async updateEmail() {
this.validateFields();
try {
await axios.post(this.updateEmailPath, {
password: this.password,
email: this.email
});
} catch (e) {
console.log(e.message);
}
},
測驗運行時在控制臺輸出:
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 | });
uj5u.com熱心網友回復:
對于 Vue 2,必須在安裝組件之前模擬該方法,因為組件.methods僅在安裝時才被連接:
test('should submit form', async () => {
const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ?
let wrapper = mount(UpdateEmail);
// const mockedFormSubmit = jest.spyOn(UpdateEmail.methods, 'updateEmail'); ?
?
});
演示
在 Vue 3 中,可以直接在掛載后模擬方法wrapper.vm(從 Vue 3.2.31 開始)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444705.html
