ES2016类,Sinon存根构造器

我正在试着用一个超级电话来剔除,而且我没有太多的运气。 任何想法,为什么这是行不通的?

运行Node 6.2.2,这可能是其实现类/构造函数的一个问题。

.babelrc文件:

{ "presets": [ "es2016" ], "plugins": [ "transform-es2015-modules-commonjs", "transform-async-to-generator" ] } 

testing:

 import sinon from 'sinon'; class Foo { constructor(message) { console.log(message) } } class Bar extends Foo { constructor() { super('test'); } } describe('Example', () => { it('should stub super.constructor call', () => { sinon.stub(Foo.prototype, 'constructor'); new Bar(); sinon.assert.calledOnce(Foo.prototype.constructor); }); }); 

结果:

 test AssertError: expected constructor to be called once but was called 0 times at Object.fail (node_modules\sinon\lib\sinon\assert.js:110:29) at failAssertion (node_modules\sinon\lib\sinon\assert.js:69:24) at Object.assert.(anonymous function) [as calledOnce] (node_modules\sinon\lib\sinon\assert.js:94:21) at Context.it (/test/classtest.spec.js:21:18) 

注意 :这个问题似乎只发生在构造函数中。 我可以窥探从父类inheritance的方法没有任何问题。

你需要spy而不是stub

sinon.spy(Foo.prototype, 'constructor');

 describe('Example', () => { it('should stub super.constructor call', () => { const costructorSpy = sinon.spy(Foo.prototype, 'constructor'); new Bar(); expect(costructorSpy.callCount).to.equal(1); }); }); 

*****更新******以上没有按预期工作,我加了这个方法,现在正在工作。

  describe('Example', () => { it('should stub super.constructor call', () => { const FooStub = spy(() => sinon.createStubInstance(Foo)); expect(FooStub).to.have.been.calledWithNew; }); }); 

它也不适用于我。 我设法解决了这个问题,我也使用间谍:

 class FakeSchema { constructor(newCar) { this.constructorCallTest(); this.name = newCar.name; } constructorCallTest() { mochaloggger.log('constructor was called'); } } // spy that tracks the contsructor call var fakeSchemaConstrSpy = sinon.spy(FakeCarSchema.prototype,'constructorCallTest'); 

希望有帮助

如果您在浏览器环境中,也可以使用以下方法:

 let constructorSpy = sinon.spy(window, 'ClassName'); 

例如,这将与茉莉花一起工作。

摩卡反而运行在Node环境中,没有window 。 你要找的variables是global