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

231
Vistas
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 Respuestas
Responde la pregunta

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 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