Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

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

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos