Búsqueda de sitios web

typescript - NestJS + Mongoose: ¿Cómo probar document(data).save()?


Dado que estoy usando algunas abstracciones, el código aquí simplemente recibe un Usuario, lo convierte a un formato de Mongo (es decir, agrega un guion bajo al id generado en otro lugar), lo guarda y luego devuelve el Usuario guardado sin el guion bajo en el 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);
  }

La prueba que estoy intentando:

  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);
  });

Los problemas:

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)

Intentar usar "new" también es imposible:

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"'.

Probablemente podría cambiar la implementación... pero realmente me gustaría averiguar qué hacer en esta situación... ¿cómo debería simular esa función?

Respuesta #1

Después de rendirme por un tiempo, volví e hice esto:

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

cambiado de new service(doc).save() a service.create(doc)

la prueba aprobada se convirtió en:

  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 );
  } );

con esto... 100% de cobertura. GENIAL.

Artículos relacionados