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

288
Vistas
How can I mock a function which is in other file and that return a promise?

I'm writing a Jest test. I need to test a function that calls a function in another .js file. This called function returns a promise that resolves to a string. When I start the test I get the error "file.function is not a function", where instead of "file" I have the name of the imported js file and instead of "function" I have the name of the function that return the promise.

Below my test:

test('test', () => {

     jest.mock('../file', () => {
         function: jest.fn().mockReturnValue('Returned String')
     });

     myFunction();
     expect().toBe();

});

Explanation: first of all I mocked the module which contains the function that return a promise. With second parameter (of jest.mock) I mocked the function contained in mocked module. Next I call the function that I want to test (this function will call mocked function). Finally, I test the expectations. Someone can help me, please. I don't know how I can resolve, thanks to all.

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

0

jest.mock should be at the same level as imports. If you need to test multiple cases just mock the returned/resolved value each time.

import { myFunction } from './fn';
import { function } from '../file';
jest.mock('../file', () => {
    function: jest.fn(),
});

describe('myFunction tests', () => {
  describe('With returned string', () => {
    beforeEach(() => {
      function.mockReturnValue('Returned String');
    });

    it('should do sth', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });

  describe('With returned number', () => {
    beforeEach(() => {
      function.mockReturnValue(7);
    });

    it('should do other thing', () => {
      myFunction();
      // expect(...).toBe(...);
    });
  });
});
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