Mongodb 如何使用jest监视mongoose的Schema.virtual?

Mongodb 如何使用jest监视mongoose的Schema.virtual?,mongodb,mongoose,jestjs,nestjs,Mongodb,Mongoose,Jestjs,Nestjs,我已经定义了mongoose模式,如何监视模式并确保在我的单元测试中调用virtual方法 const UserSchema=新模式( { 用户名:SchemaTypes.String, 密码:SchemaTypes.String, 电子邮件:SchemaTypes.String, 名字:{type:SchemaTypes.String,必需:false}, lastName:{type:SchemaTypes.String,必需:false}, 角色:[ {type:SchemaTypes.S

我已经定义了mongoose模式,如何监视模式并确保在我的单元测试中调用
virtual
方法

const UserSchema=新模式(
{
用户名:SchemaTypes.String,
密码:SchemaTypes.String,
电子邮件:SchemaTypes.String,
名字:{type:SchemaTypes.String,必需:false},
lastName:{type:SchemaTypes.String,必需:false},
角色:[
{type:SchemaTypes.String,枚举:['ADMIN','USER'],必需:false},
],
//createdAt:{type:SchemaTypes.Date,必需:false},
//updatedAt:{type:SchemaTypes.Date,必需:false},
},
{
时间戳:对,
toJSON:{
虚拟的:真的
}
},
);
UserSchema.virtual('name').get(函数(){
返回`${this.firstName}${this.lastName}`;
});
UserSchema.virtual('posts'{
参考:“职位”,
localField:“\u id”,
foreignField:“createdBy”,
});

我找到了解决这个问题的简单方法,但我必须重构代码

将虚拟方法提取到独立函数中

函数名gethook(){
返回`${this.firstName}${this.lastName}`;
}
UserSchema.virtual('name').get(nameGetHook);
并设置一个模拟上下文以在jest中运行函数

const getMock=jest.fn().mockImplementationOnce(cb=>cb)
const virtualMock=jest.fn().mockImplementationOnce(
(名称:字符串)=>({
获取:getMock
})
);
描述('UserSchema',()=>{
它('应该称为Schame.virtual',()=>{
expect(UserSchema).toBeDefined()
expect(getMock).toBeCalled()
expect(getMock).toBeCalledWith(anyFunction())
expect(virtualMock).toBeCalled()
expect(virtualMock).tohaven已通过(1,“name”)调用
expect(virtualMock).tohaven调用时使用(2,“posts”,“foreignField”:“createdBy”,“localField”:“u id”,“ref”:“Post”})
期望(virtualMock)。等待调用时间(2)
});
});
...
检查我的完整示例代码