【问题标题】:How do I mock Mongoose's "lean()" query with Jest and NestJS?如何使用 Jest 和 NestJS 模拟 Mongoose 的“lean()”查询?
【发布时间】:2021-04-01 09:56:59
【问题描述】:

我有一个 Person 实体,它有自己的 Repository 类,我想对其进行测试。此存储库类按照 NestJS 文档中的建议注入 Mongoose 模型,如下所示:

    @InjectModel(Person.name)
    private model: Model<PersonModel>

我要测试的代码是类似于const res = await this.model.find().lean();的查询

不过,我的问题是在测试lean() 查询时,因为它是find() 方法的链式函数。我能够尽可能地做到这一点,但是在嘲笑它时,我遇到了一些类型冲突:

const modelMockObject = {
  find: jest.fn(),
  findOne: jest.fn(),
  findOneAndUpdate: jest.fn(),
  updateOne: jest.fn(),
};

// ...

  let MockPersonModel: Model<PersonModel>;

  beforeEach(async () => {
    const mockModule: TestingModule = await Test.createTestingModule({
      providers: [
        ...,
        {
          provide: getModelToken(Person.name),
          useValue: modelMockObject,
        },
      ],
    }).compile();

    MockPersonModel = mockModule.get<Model<PersonModel>>(
      Person.name,
    );
  }); 

// ...
// Inside a describe/it test...

      const personModel = new MockPersonModel({
        name: 'etc'
      });

      jest.spyOn(MockPersonModel, 'findOne').mockReturnValueOnce({
        lean: () => ({ exec: async () => personModel }),
      });

linter 在personModel(倒数第二行)上通知的错误如下:

Type 'Promise<PersonModel>' is not assignable to type 'Promise<P>'.
  Type 'PersonModel' is not assignable to type 'P'.
    'P' could be instantiated with an arbitrary type which could be unrelated to 'PersonModel'.ts(2322)
index.d.ts(2100, 5): The expected type comes from the return type of this signature.

非常感谢您的帮助!

【问题讨论】:

    标签: javascript typescript mongoose jestjs nestjs


    【解决方案1】:

    也许对你来说太晚了,但对于下一个像我一样寻求解决这个问题的人来说。

    您可以简单地使用 mockImplementation: 例如:

    MockPersonModel.findOne.mockImplementationOnce(() => ({
        lean: jest.fn().mockReturnValue(personModel),
    }));
    
    

    您可以在此处查看有关此实现的更多详细信息:

    my simple test

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-15
      • 2020-07-16
      • 2020-08-28
      • 2022-08-24
      • 2020-11-04
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      相关资源
      最近更新 更多