2016-04-07 13 views
0

私はmocha/chai/sinon、および一般的なテストでは初めてです。私は基本的なエクスプレスサーバー、約束を返す関数、そして鼻を濡らすための基本的な続行設定をテストすることに成功しました。私はスパイ/スタブ/モックで立ち往生しています。私の拳しゃっくりは、そのグロブをチェックしようとしているsinonでネストされた依存関係を偵察するにはどうすればいいですか?

は外部モジュールで呼び出されました:上記

// in utils-test.js 
var utils = require('utils.js'); 
var glob = require('glob'); 

describe('Utils', function() { 
    describe('funToTest method', function() { 
    const callback = sinon.spy(); 
    const globSpy = sinon.spy(glob); 

    before(function (done) { 
     utils.funToTest('Files:', callback); 
     done(); 
    }); 

    // This PASSES fine 
    it ('should call our callback twice', function() { 
     expect(callback).to.have.been.calledTwice; 
    }); 

    // This NOT SO MUCH 
    it('should call glob once', function() { 
     expect(globSpy).to.have.been.calledOnce; 
    }); 
)}; 
)}; 

//in utils.js 
var glob = require('glob'); 

module.exports = { 
    funToTest: function (msg, callback) { 
    console.log(msg); 
    glob('*md', { 
     cwd: 'files/' 
    }, function (err, files) { 
     console.log(files); 
    }); 
    callback(); 
    callback(); 
    } 
}; 

モカ/チャイ/ sinon/sinon-チャイの組み合わせを使用してアサーションエラーで失敗する:

AssertionError: expected glob to have been called exactly once, but it was called 0 times 

だから、utils.funToTのグロブの依存性呼び出されるかどうかを確認するには?これまでの任意のポインタ用として

おかげで...

+0

"expect(globspy.calledOnce).to.be.true"を試しましたか? –

答えて

0

あなたはグロブモジュール自体をスパイしている、あなたのfunToTestメソッド内ではないグロブコール。問題はglob呼び出しが実装の詳細であり、テスト内から実際にアクセスできないということです。 globコールバックの引数を渡して、スパイまたはスタブで呼び出されたことをテストする必要があります。

//in utils.js 
var glob = require('glob'); 

module.exports = { 
    funToTest: function (msg, globCb, callback) { 
    glob('*md', { 
     cwd: 'files/' 
    }, globCb); 
    callback(); 
    callback(); 
    } 
}; 

// in utils-test.js 
var utils = require('utils.js'); 
var glob = require('glob'); 

describe('Utils', function() { 
    describe('funToTest method', function() { 
    const callback = sinon.spy(); 
    const globCb = sinon.spy(); 

    const err = {err: 'Error'}; 
    const files = ['file1', 'file2']; 

    before(function (done) { 
     utils.funToTest('Files:', globCb, callback); 
     done(); 
    }); 

    // Should still pass 
    it ('should call our callback twice', function() { 
     expect(callback).to.have.been.calledTwice; 
    }); 

    // Passes with correct args 
    it('should call glob once', function() { 
     expect(globCb).to.have.been.calledOnce; 
     // inspect the arg values with .calledWithArgs 
     expect(globCb.calledWithArgs(err, files)).to.be.true; 
     // inspect the arg values with .getCall(index) (actually grabs the call args on the first call to globSpy) 
     expect(globCb.getCall(0).args[0]).to.equal(err); 
     expect(globCb.getCall(0).args[1]).to.equal(files); 
    }); 
)}; 
)}; 
関連する問題