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

标签 mongodb mongoose jestjs nestjs

我已经定义了一个 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/

相关文章:

javascript - 密码在保存到数据库之前不会进行哈希处理

javascript - 如何使用 Mongoose 获得分组数据的总和

vue.js - 测试Vue组件时如何mock side plugin?

firebase - Jest 测试在调用模拟的 firebase 函数之前完成,因此失败

javascript - 当我尝试测试我的重试 util 函数时,jest.advanceTimersByTime 不起作用

node.js - mongo 可以 upsert 数组数据吗?

mongodb - 通过 _id 在 mongodb 数据库中的对象数组上查找

mongodb - 如何在 MongoDB 3.4.0 中使用 $graphLookup 创建 View ?

javascript - 文档和子文档的 $sum 按 "$author"(MongoDB)

javascript - Mongoose - 保持模型与变化相关联