2016-10-26 3 views
4

私はsinonとes2016でスーパーコールをスタブしようとしていますが、私は運があまりありません。なぜこれが動作していないすべてのアイデア?ES2016 Class、Sinon Stubコンストラクタ

ノード6.2.2を実行すると、これはクラス/コンストラクタの実装に関する問題である可能性があります。

.babelrcファイル:

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

テスト:

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) 

:この問題は、唯一のコンストラクタのために起こるようです。私は親クラスから継承したメソッドを何の問題もなく偵察することができます。

あなたが 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); 
    }); 
}); 

に必要

答えて

1

期待通りに更新****** 以上が働いていなかった*****、私はこの方法を追加しています今働いている。

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

面白いです等しい1 ' に0を期待 - 私は上記のあなたの例をコピーしました。 – klyd

+0

うーん...面白いですが、新しい変更で更新されました。回避策だと思ってください:) – anoop

+0

あなたの新しい例は、私のノード6.2.2とbabel es2016のプリセットではまだ動作していないようです。 – klyd

0

私にとってもうまくいきません。私は、私もスパイを使用して、私の作品の回避策を管理する:あなたは、ブラウザの環境の場合

0

役立ちました

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'); 

たとえば、これはJasmineで動作します。

代わりにノード環境ではMochaが実行されますが、windowはありません。 `てAssertionError:あなたが探しているはずだ変数は、これは私のために動作しませんでしたglobal

関連する問題