【问题标题】:How to use jest to spy on Schema.virtual of mongoose?如何使用 jest 来监视 Schema.virtual 的猫鼬?
【发布时间】:2020-11-12 19:24:45
【问题描述】:

我已经定义了一个 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',
});

【问题讨论】:

    标签: mongodb mongoose jestjs nestjs


    【解决方案1】:

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

    将虚方法提取为独立函数。

    function nameGetHook() {
      return `${this.firstName} ${this.lastName}`;
    }
    
    UserSchema.virtual('name').get(nameGetHook);
    

    并设置一个模拟上下文以开玩笑地运行该函数。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2018-11-18
      • 2011-10-25
      • 2021-01-02
      • 1970-01-01
      • 2019-06-12
      • 2012-02-19
      相关资源
      最近更新 更多