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

406
Vistas
Jest mock a function which instantiates a class and its constructor has an error callback, callback not invoked in error case

I need to satisfy SonarQube for the error case in the code below.

When I run the test code though, it will not fail.

index.js

const mod = require('mod')

function get_modclass(data) {   
    let modclass = new ModClass(data, function(err) {
        if (err) {
            console.log('ERROR: ' + err);
            throw err
        }
    })
    
    return modclass
}

index.spec.js


describe('Test get_modclass', () => {
  jest.resetModules()
  jest.clearAllMocks()

  test('Should fail get_modclass', () => {
    const idx = require('./index.js');
    const mod = require('mod')
   
    jest.mock('mod', () => ({
       ModClass: jest.fn(() => ({
                constructor: (_data, cb) => cb('err'),
       }))
    }))


    try {
        let mc = idx.get_modclass("abc")
    } catch(e) {
       expect(e.message).toEqual('some message')
    }

  })
})

Rather than cb('err') I have tried sending cb(new Error('err message')) to the constructor, but it will still not fail. When I debug, it goes into the idx.get_modclass function, but from there it goes direct to return modclass instead of to the if of the callback.

Help appreciated.

Thanks!

about 4 years ago · Juan Pablo Isaza
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