【问题标题】:Mock entire es6 class except constructor in Jest?在 Jest 中模拟除构造函数之外的整个 es6 类?
【发布时间】:2016-04-09 18:32:50
【问题描述】:

如果我有一个 A 类,像这样:

class A{
    constructor(foo){
        this.foo = foo;
    }

    doStuff(){
        //Code protected by an NDA, they'll nuke my house if I tell you what it does.
    }

    nukeHouse(){
        //The implementation of this is somewhat buggy...
    }
}

我希望 A 类的用户能够访问this.foo,所以我不想模拟构造函数。所有其他方法都应该被模拟。我可能可以手动说A.prototype.doStuff = jest.genMockFunction()ù, and do the same forA.prototype.nukeHouse`,但我希望有一种方法可以做到这一点,而不必每次向 A 添加方法时都更新模拟代码。

有没有办法做到这一点?

【问题讨论】:

    标签: javascript mocking jestjs ecmascript-6


    【解决方案1】:

    我想通用的解决方案是简单地遍历 prototype 并为每个属性创建一个模拟函数:

    var A = require.requireActual('./A');
    
    Object.getOwnPropertyNames(A.prototype).forEach(function(prop) {
      A.prototype[prop] = jest.genMockFunction();
    });
    
    module.exports = A;
    

    如果类扩展另一个类,这可能会更困难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 2020-01-08
      • 2017-11-21
      • 2019-08-19
      • 2020-05-06
      • 2021-04-05
      • 2018-05-04
      相关资源
      最近更新 更多