NestJS + Mongoose: How to test for document(data).save()?

Viewed 1086

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?

1 Answers

After giving up for a while, came back and did this:

async saveUser ( user: User ): Promise<User> {
    const mongoUser = this.getMongoUser(user);
    const savedMongoUser = await this.service.create( mongoUser );
    return this.toUserFormat(savedMongoUser);
}

changed from new service(doc).save() to service.create(doc)

the passing test became:

  it( 'should save new user', async () => {
    jest.spyOn( model, 'create' ).mockImplementation(
      jest.fn().mockResolvedValueOnce( mockMongoFormat )
    );
    const foundMock = await service.saveUser( mockUserFormat );
    expect( foundMock ).toEqual( mockUserFormat );
  } );

with this... 100% coverage. NICE. enter image description here

Related