Since I'm using some abstractions, the code here just receive an User, changes that to a Mongo format (aka adds a underslash to the id generated elsewhere), saves and then returns the saved User without the underslash on the id:
constructor(
@InjectModel('User')
private readonly service: typeof Model
) { }
async saveUser(user: User): Promise<User> {
const mongoUser = this.getMongoUser(user);
const savedMongoUser = await new this.service(mongoUser).save();
return this.toUserFormat(savedMongoUser);
}
The test I'm trying:
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MongoUserRepository,
{
provide: getModelToken('User'),
useValue: { ... }, // all used functions with jest.fn()
},
],
}).compile();
service = module.get<MongoUserRepository>(MongoUserRepository);
model = module.get<Model<UserDocument>>(getModelToken('User'));
});
it('should save new user', async () => {
jest.spyOn(model, 'save').mockReturnValue({
save: jest.fn().mockResolvedValueOnce(mockMongoFormat)
} as any);
const foundMock = await service.saveUser(mockUserFormat);
expect(foundMock).toEqual(mockUserFormat);
});
The problems:
No overload matches this call.
Overload 1 of 4, '(object: Model<UserDocument, {}>, method: "model" | "remove" | "deleteOne" | "init" | "populate" | "replaceOne" | "update" | "updateOne" | "addListener" | "on" | ... 45 more ... | "where"): SpyInstance<...>', gave the following error.
Argument of type '"save"' is not assignable to parameter of type '"model" | "remove" | "deleteOne" | "init" | "populate" | "replaceOne" | "update" | "updateOne" | "addListener" | "on" | "once" | "removeListener" | "off" | "removeAllListeners" | ... 41 more ... | "where"'.
Overload 2 of 4, '(object: Model<UserDocument, {}>, method: "collection"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.
Argument of type '"save"' is not assignable to parameter of type '"collection"'.ts(2769)
Trying to use "new" is also a no go:
No overload matches this call.
Overload 1 of 4, '(object: Model<UserDocument, {}>, method: "find" | "watch" | "translateAliases" | "bulkWrite" | "model" | "$where" | "aggregate" | "count" | "countDocuments" | ... 46 more ... | "eventNames"): SpyInstance<...>', gave the following error.
Argument of type '"new"' is not assignable to parameter of type '"find" | "watch" | "translateAliases" | "bulkWrite" | "model" | "$where" | "aggregate" | "count" | "countDocuments" | "estimatedDocumentCount" | "create" | "createCollection" | ... 43 more ... | "eventNames"'.
Overload 2 of 4, '(object: Model<UserDocument, {}>, method: "collection"): SpyInstance<Collection, [name: string, conn: Connection, opts?: any]>', gave the following error.
Argument of type '"new"' is not assignable to parameter of type '"collection"'.
I could probably change the implementation... but would really like to find out what to do in this situation... how should I mock that function?
