我已经定义了一个 mongoose Schema,如何监视 Schema 并确保 virtual
方法在我的单元测试中被调用。
const UserSchema = new Schema(
{
username: SchemaTypes.String,
password: SchemaTypes.String,
email: SchemaTypes.String,
firstName: { type: SchemaTypes.String, required: false },
lastName: { type: SchemaTypes.String, required: false },
roles: [
{ type: SchemaTypes.String, enum: ['ADMIN', 'USER'], required: false },
],
// createdAt: { type: SchemaTypes.Date, required: false },
// updatedAt: { type: SchemaTypes.Date, required: false },
},
{
timestamps: true,
toJSON: {
virtuals: true
}
},
);
UserSchema.virtual('name').get(function () {
return `${this.firstName} ${this.lastName}`;
});
UserSchema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'createdBy',
});
最佳答案
我找到了一个简单的解决方案来解决这个问题,但我必须重构我的代码。
将虚方法提取为独立函数。
function nameGetHook() {
return `${this.firstName} ${this.lastName}`;
}
UserSchema.virtual('name').get(nameGetHook);
并设置一个模拟上下文对于Jest地运行该函数。
const getMock = jest.fn().mockImplementationOnce(cb => cb)
const virtualMock = jest.fn().mockImplementationOnce(
(name: string) => ({
get: getMock
})
);
describe('UserSchema', () => {
it('should called Schame.virtual ', () => {
expect(UserSchema).toBeDefined()
expect(getMock).toBeCalled()
expect(getMock).toBeCalledWith(anyFunction())
expect(virtualMock).toBeCalled()
expect(virtualMock).toHaveBeenNthCalledWith(1, "name")
expect(virtualMock).toHaveBeenNthCalledWith(2, "posts", { "foreignField": "createdBy", "localField": "_id", "ref": "Post" })
expect(virtualMock).toBeCalledTimes(2)
});
});
...
检查我的完整示例代码 here .
关于mongodb - 如何使用 jest 监视 mongoose 的 Schema.virtual?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63047976/