I have defined a mongoose Schema, how to spy on Schema and make sure the virtual method is called in my unit test.
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',
});