Javascript 模拟整个es6类,除了开玩笑的构造函数?
如果我有a级,像这样:Javascript 模拟整个es6类,除了开玩笑的构造函数?,javascript,mocking,jestjs,ecmascript-6,Javascript,Mocking,Jestjs,Ecmascript 6,如果我有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 bu
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()ù,并对A.prototype.nukeHouse`执行同样的操作,但我希望有一种方法可以做到这一点,而不必每次向A添加方法时都更新模拟代码
有办法做到这一点吗?我想一般的解决方案是简单地迭代原型
并为每个属性创建一个模拟函数:
var A = require.requireActual('./A');
Object.getOwnPropertyNames(A.prototype).forEach(function(prop) {
A.prototype[prop] = jest.genMockFunction();
});
module.exports = A;
如果该类扩展了另一个类,这可能会更加困难