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

233
Visualizações
How to test and mocking a function Nodejs with Jest

I want to test a function. This function also need other function, but this other function will be mocked with jest.

Here is my function

translate(args, cb) {
    const transid = args.transid;
    const language = args.language;
    const defaultValue = args.defaultValue || '';

    if (transid === null || transid === '') {
      return cb(new Error('Error. Need TransiD'));
    }
    if (language === null || language === '') {
      return cb(new Error('Error. Need language'));
    }

    return this.translation(transid, language, defaultValue)
      .then((res) => {
        return cb(null, res);
      });
  }

That function need function 'translation'. in testing process, i will mocking it.

Here is my function for testing

describe('Translator', () => {
  describe('translate', () => {

    it('Should return translated value', (done) => {
      const args = {
        transid: 1,
        language: 'EN',
        defaultValue: 'defaultValue',
      }
      const cb = jest.fn((err, res) => {

      });
      translator.translation = jest.fn((transid, language, defaultValue) => {
        // done();
      })

      translator.translate(args, cb);
      done();
    });
  })
})

I am still confusing how to test that function using Jest and also mocking the required dependencies.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

A couple of things I can see:

  • You can avoid using Jest’s done function by returning the Promise chain, which Jest will use to determine when a test is complete.
  • You don't need to mock the implementation of the functions, just their return values. You might want to create an additional test that does mock the implementation behavior, but its good to start with just controlling their output.

Here's how the test might look:

describe('Translator', () => {
  describe('translate', () => {
    it('Should return translated value', () => {
      const args = {
        transid: 1,
        language: 'EN',
        defaultValue: 'defaultValue',
      }

      const cb = jest.fn();

      const res = {};

      translator.translation = jest.fn()
        .mockReturnValue(Promise.resolve(res));

      return translator.translate(args, cb)
        .then(() => {
          expect(translator.translation).toHaveBeenCalledTimes(1);
          expect(translator.translation)
            .toHaveBeenCalledWith(1, 'EN', 'defaultValue');

          expect(cb).toHaveBeenCalledTimes(1);
          expect(cb).toHaveBeenCalledWith(null, res);
        });
    });
  })
})
over 4 years ago · Santiago Trujillo 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