我有一个 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),
}));
您可以在此处查看有关此实现的更多详细信息:
关于javascript - 如何使用 Jest 和 NestJS 模拟 Mongoose 的 "lean()"查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65413061/