模拟除了Jest中的构造函数之外的整个es6类

Mock entire es6 class except constructor in Jest?

本文关键字:es6 构造函数 Jest 模拟      更新时间:2023-09-26

如果我有一个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 for A.prototype.nuckeHouse,但我希望有一种方法可以做到这一点,而不必每次向A.添加方法时都更新嘲笑代码

有办法做到这一点吗?

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

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

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