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

180
Vistas
Mocked class method only returns undefined

I'm testing a React class component which relies on a service for retrieving the user auth.

  async populateState() {
    const result = await authService.getUserAuthenticationStatus();
    const { user, isAuthenticated } = result;
    this.setState({
      isAuthenticated,
      user
    });
  }

So, I would like to mock the return value for getUserAuthenticationStatus like so:

jest.mock('./components/api-authorization/AuthorizeService');

beforeAll(() => {
  jest.spyOn(AuthService, 'getUserAuthenticationStatus').mockReturnValue(
    Promise.resolve({
      isAuthenticated: true,
      user: {}
    })
  );
});

The problem here, is that when running my tests, the method keeps returning undefined rather than the mock value I had set up in my test. If we take a quick look at the exported member, we can see the class is being instantiated and then exported. Could this be the issue?

const authService = new AuthorizeService();
export default authService;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think jest.mock is unnecessary here. You can simply spyOn the method since you already have an instance.

beforeAll(() => {
  jest.spyOn(authService, 'getUserAuthenticationStatus')
    // Returns promise no need to add manually
    .mockResolvedValue({ isAuthenticated: true, user: {} });
});

// And make sure you clear the mocks in the end. 
afterAll(() => jest.clearAllMocks());

Note: you are spying on the authService, not the AuthService

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