代码之家  ›  专栏  ›  技术社区  ›  Hantsy

如何使用jest监视猫鼬的Schema.virtual?

  •  2
  • Hantsy  · 技术社区  · 5 年前

    我定义了一个mongose 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',
    });
    
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   Hantsy    5 年前

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

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

    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 .