【发布时间】: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