简体   繁体   中英

Jest: Mocking constructor to return error

I'm having trouble trying to mock a class constructor in jest.

I have some code similar to this where I want to have code coverage for the catch

   try {
    redis = new Redis(params); 
   }catch(err){
    return reject(new Error());
   }

The mock I'm trying to create in a unit test so that "new Redis" throws an error includes something like this:

jest.mock('ioredis', () => {
  return jest.fn().mockImplementation(() => {
    return {
      constructor: () => {
        throw new Error();
      },
    };
   });
 });

The documentation doesn't seem to have a good example for mocking constructors.

The documentation explains how classes are mocked. It doesn't show constructor method because it's irrelevant in these scenarios. In JavaScript, constructor is a special method that is normally equal to constructor function itself, Class === Class.prototype.constructor . constructor is used in inheritance but normally isn't called directly, so mocking or even mentioning it in this scenario doesn't make sense. It's constructor function that is called and it should be mocked instead:

jest.mock('ioredis', () => {
  return jest.fn().mockImplementation(() => {
    throw new Error();
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM