[英]How to stub an extended ES6 class' constructor with Sinon
So I'm having a few issues with stubbing constructors, and more-so inherited classes constructors... I'll start with some sample code snippets: 因此,我在存根构造函数方面遇到了一些问题,在继承类构造函数中又遇到了更多问题……我将从一些示例代码片段开始:
Parent.js Parent.js
module.exports = class Parent {
constructor (){
// code I don't want to run during tests
}
}
MyClass.js MyClass.js
let Parent = require('path/to/Parent');
module.exports = class MyClass extends Parent {
// no overridden constructor
}
Mocha Test 摩卡测试
let MyClass = require('path/to/MyClass')
...
test('test1', (done) => {
// I want to stub the MyClass/Parent constructor before creating a new instance
// of MyClass so that the constructor code in Parent doesn't run
let myClass = new MyClass();
// assertions 'n' stuff
return done();
});
...
I've tried a few things already but always find that the code in Parent constructor gets run regardless of what I do... I have a feeling it might have something to do with MyClass requiring Parent before a get a chance to stub it. 我已经尝试了一些方法,但始终发现无论我做什么,都可以运行Parent构造函数中的代码...我感觉这可能与MyClass有关,而MyClass要求Parent才有可能将其存根。
I've also tried using rewire to replace the variable in MyClass, but not joy there either; 我也尝试过使用rewire来替换MyClass中的变量,但是那里也不高兴; eg 例如
let MyClass = rewire('path/to/MyClass');
MyClass.__set__('Parent', sinon.stub());
Any suggestions/help on how I might achieve what I'm trying to do here? 关于如何实现此处要实现的目标的任何建议/帮助吗?
I haven't used rewire so I'm not sure why it doesn't work but stubbing the parent constructor would work fine using proxyquire : 我还没有使用过rewire,所以我不确定为什么它不起作用,但是使用proxyquire将父构造函数存根可以很好地工作:
const MockParent = sinon.stub()
const MyClass = proxyquire('../../some/path', {
'./Parent': MockParent
})
module.exports = class MyClass extends Parent {
// no overridden constructor
}
Be equal to: 等于:
module.exports = class MyClass extends Parent {
constructor (...args) {
super(...args) // be equal to Parent.call(this, ...args)
}
}
So, the processes are new MyClass() -> MyClass constructor() -> Parent.call() -> Parent constructor() 因此,这些过程是新的MyClass()-> MyClass构造函数()-> Parent.call()->父构造函数()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.