javascript - 如何使用 Jest 和 NestJS 模拟 Mongoose 的 "lean()"查询?

标签 javascript typescript mongoose jestjs nestjs

我有一个 Person 实体,它有自己的 Repository 类,我想测试它。这个存储库类按照 NestJS 文档中的建议注入(inject) 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.

非常感谢您的帮助!

最佳答案

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

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

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

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

my simple test

关于javascript - 如何使用 Jest 和 NestJS 模拟 Mongoose 的 "lean()"查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65413061/

相关文章:

javascript - 预检响应在 axios 中没有 HTTP ok 状态

javascript - 更改 div 中的图像,但无法给出它和 javascript 变量 id

javascript - 禁用一个事件并再次在 jQuery 中启用该事件

javascript - 我不断收到 [$injector :modulerr] in angularJS

javascript - 在组件中作为 prop 访问调度函数

javascript - 仅使用几个关键字在 mongodb 中搜索

node.js - 在 Mongoose 中使用动态字段

typescript - Typed Entities with breezejs for typescript 或替代 VS 的扩展以从 c# 类创建接口(interface)?

typescript - 如何将 typescript npm 模块导入语法转换为 ECMA2015 模块导入语法

node.js - 无法通过 NPM 安装 Mongoose