Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

399
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!