【发布时间】:2020-06-14 17:57:36
【问题描述】:
尝试测试具有外部 API 调用的 Vue 组件方法以及返回我试图模拟的 Promise 的响应。这是我在删除其他细节后得到的:
Component.vue
import UserAPI from '../../mixins/UserAPI'
export default {
mixins:
UserAPI
,
methods:
AddUserInfo(id){
if (this.$options.cachedUsers.length === 0 || (!this.$options.cachedUsers.map(u => u.userId.includes(id))
{
this.fetchUserById(id) <--this is a call I am trying to mock
.then( user=> {
if (user)
{
this.$options.cahedUsers.push(user);
}
})
.fail( errors => {
throw Errors(error)
});
}
return this.$options.cachedUsers.find(el => el.id === id);
}
}
Component.spec.js
it('should add users', () => {
wrapper.vm.$options.cachedUsers = [];
const response = { userId: "5ebdae27eb5311e0f7d2f511", userName: "admin", displayName: "Administrator" };
wrapper.vm.fetchUserById = (id) => {
return {
then: () => jest.fn(usr => wrapper.vm.$options.cachedUsers.push(response)),
fail: () => jest.fn(errors => { })
};
};
status = wrapper.vm.AddUserInfo(user);
expect(wrapper.vm.$options.cachedUsers.length).toBe(1);
});
但是,我收到了来自测试运行程序的错误:this.fetchUserById(...).then(...).fail is not a function,这意味着我可能没有正确地模拟它。我需要修改什么才能使这个测试变为绿色?
【问题讨论】: