触发提交事件而不更新 Jest 中的调用计数Vue 测试工具
在 Vue 2.6.12
中使用 Jest:"^27.5.1"
和 "@vue/test-utils": "^1.3.0", 我正在尝试使用 jest 模拟一个
async
方法。当我断言我的方法已被调用 1 次时,它返回它尚未被调用。我做错了什么吗?
测试运行时更新电子邮件测试
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);
});
UpdateEmail 方法
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 | });
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('[email protected]')
await wrapper.find('#password').setValue('MyPassword');
await wrapper.find('form').trigger('submit.prevent');
expect(mockedFormSubmit).toHaveBeenCalledTimes(1);
});
UpdateEmail Method
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 | });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为组件的
.methods
仅在安装时才连接:对于 Vue 2,必须在安装组件之前模拟该方法, com/edit/vue2-mock-form-submit?file=tests/unit/UpdateEmail.spec.js" rel="nofollow noreferrer">demo
在 Vue 3 中,可以在挂载后模拟方法直接来自
wrapper.vm
(从 Vue 3.2.31 开始)。For Vue 2, the method must be mocked before mounting the component because the component's
.methods
are wired up only upon mounting:demo
In Vue 3, methods can be mocked post-mount directly off of the
wrapper.vm
(starting with Vue 3.2.31).