简体   繁体   English

笑话:Mocking 构造函数返回错误

[英]Jest: Mocking constructor to return error

I'm having trouble trying to mock a class constructor in jest.我在尝试开玩笑地模拟 class 构造函数时遇到了麻烦。

I have some code similar to this where I want to have code coverage for the catch我有一些与此类似的代码,我想对 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:我试图在单元测试中创建以便“新 Redis”引发错误的模拟包括如下内容:

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.该文档似乎没有 mocking 构造函数的好例子。

The documentation explains how classes are mocked.文档解释了如何模拟类。 It doesn't show constructor method because it's irrelevant in these scenarios.它不显示constructor方法,因为它在这些场景中无关紧要。 In JavaScript, constructor is a special method that is normally equal to constructor function itself, Class === Class.prototype.constructor .在JavaScript中, constructor是一个特殊的方法,通常等同于constructor function本身, 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. constructor在 inheritance 中使用,但通常不直接调用,因此 mocking 甚至在这种情况下提及它都没有意义。 It's constructor function that is called and it should be mocked instead:它是构造函数 function 被调用,它应该被模拟:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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