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

401
Visualizações
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 à 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