2016-04-07 54 views
0

我對mocha/chai/sinon以及一般測試非常陌生。我成功地測試了一個基本的express服務器,一個返回promise的函數,以及一個基本的sequelize設置來讓我的鼻子變溼;但我被困在間諜/存根/嘲笑。我該如何窺探與sinon的嵌套依賴關係

我的拳頭打嗝試圖檢查水珠被稱爲外部模塊:

//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(); 
    } 
}; 

使用摩卡/柴/興農/興農釵組合:

// 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; 
    }); 
)}; 
)}; 

以上斷言錯誤失敗:

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

那麼我該如何窺探utils.funToT中的glob依賴估計是否被調用?

感謝和以往任何指針...

+0

您是否試過「expect(globspy.calledOnce).to.be.true」? –

回答

0

你刺探glob模塊本身上,而不是你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); 
    }); 
)}; 
)};