簡體   English   中英

如何使用 Jest 和 NestJS 模擬 Mongoose 的“lean()”查詢?

[英]How do I mock Mongoose's "lean()" query with Jest and NestJS?

我有一個 Person 實體,它有自己的存儲庫 class,我想對其進行測試。 這個存儲庫 class 按照 NestJS 文檔中的建議注入 Mongoose model,如下所示:

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

我要測試的代碼是一個類似於const res = await this.model.find().lean();的查詢。

不過,我的問題是在測試 lean() 查詢時,因為它是一個鏈式 function 到 find() 方法。 我已經盡我所能,但是當涉及到 mocking 時,我遇到了一些類型沖突:

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.

非常感謝你的幫助!

也許對你來說太晚了,但對於下一個像我一樣尋求解決這個問題的人來說。

您可以簡單地使用mockImplementation :例如:

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

您可以在此處查看有關此實現的更多詳細信息:

我的簡單測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM