Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

277
Vistas
How to mock a method in the same class I'm testing in nestjs/jest

I have a service in NestJS I'm testing using @nestjs/testing in Typescript. But one of the methods depends on another, I would like to mock out the dependent method for only one test, so I can't use the ES6 class mocking, as that would override the class I'm testing with a mock.

class UsersService {
  findMany(ids) {
    return ids.map(id => this.findOne(id));
  }
  
  findOne(id) {
    return this.httpService.get(id);
  }
}

I want to test both methods, but I want to mock findOne only when I'm testing findMany.
Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You want to use spying here. Look for 'spyOn' in this documentation: https://docs.nestjs.com/fundamentals/testing near the bottom.

Here's an example I tried to cook up that's related to your posted code:

test('findMany', () => {
  const spy = new UsersService;
  // Here's the key part ... you could replace that "awesome" with something appropriate
  jest
    .spyOn(spy, 'findOne')
    .mockImplementation(() => "awesome");
  
  // Just proving that the mocking worked, you can remove this
  expect(spy.findOne()).toBe("awesome");

  const ids = ["Dio", "Lemmy"];
  expect(spy.findMany(ids)).toStrictEqual(["awesome", "awesome"])
});

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda