Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

283
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda