2017-10-19 7 views
2

私は、インポートされたクラスをインスタンス化し、それらのインスタンスのメソッドを非同期に呼び出すモジュールを持っています。テストされたインスタンスごとのモック依存クラス

テストケースごとにこれらのメソッドを個別にモックすることができます。テストの最後にモックを確実に復元できないので、これらのモックはテストケース内で作成されるインスタンスにのみ意味があります。

例:私はCASE1でBとCを模擬し、同期的にそれらを復元した場合ケース2は、非同期コンテキストでCのインスタンス化する前に実行されるため

// tested class 
import B from './b'; 
import C from './c'; 

export default class A { 
    someFunction() { 
    let instanceB = new B(); 
    return instanceB.doSomething() 
     .then(() => this.doSomethingElse()) 
     .then((data) => { 
     // async context, other tests will start before this. 
     let instanceC = new C(data); 
     }); 
    } 
} 

// test 
import A from './a'; 
describe('test',() => { 
    it('case1',() => { 
    a = new A(); 
    // Mock B, C with config1 
    return a.someFunction().then(() => {/* asserts1 */ }); 
    }) 
    it('case2',() => { 
    a = new A(); 
    // Mock B, C with config2 
    return a.someFunction().then(() => {/* asserts2 */ }); 
    }) 
}) 

、Cのconfigは上書きされます。 同じ理由で、asserts1の後にモックを非同期に復元することはできません。

同様の質問があります:Stubbing a class method with Sinon.jsHow to mock dependency classes for unit testing with mocha.js? しかし、それらは非同期モックの問題をカバーしていません。

答えて

0

私は(かなりではない)コンストラクタインジェクションで終わった。非同期の工場をテストしたり書いたりする全く別のアプローチを含め、より良い方法があれば、私は喜んで同意します。

// tested class 
import B_Import from './b'; 
import C_Import from './c'; 

let B = B_Import; 
let C = C_Import; 
export function mock(B_Mock, C_Mock) { 
    B = B_Mock || B_Import; 
    C = C_Mock || C_Import; 
} 

export default class A { 
    someFunction() { 
    let instanceB = new B(); 
    return instanceB.doSomething() 
     .then(() => this.doSomethingElse()) 
     .then((data) => { 
     // async context, other tests will start before this. 
     let instanceC = new C(data); 
     }); 
    } 
} 


// test 
import A, { mock as mockB } from './a'; 

setupMockB = (cfg, mockCallback) => { 
    const ClassMock = class { 
     constructor() { 
      // use cfg 
     } 
     doSomething() {} 
    } 
    if(mockCallback) {mockCallback(ClassMock.prototype);} 
    mockB(ClassMock, null) 
} 

describe('test',() => { 
    afterEach(() => mockB()) 
    it('case1',() => { 
    a = new A(); 
    setupMockB(cfg1, (mb) => sinon.stub(mb, 'doSomething').resolves()) 
    return a.someFunction().then(() => { /* asserts1 */ }); 
    }) 
    it('case2',() => { 
    a = new A(); 
    setupMockB(cfg2, (mb) => sinon.stub(mb, 'doSomething').rejects()) 
    return a.someFunction().then(() => { /* asserts2 */ }); 
    }) 
}) 
関連する問題