簡體   English   中英

為什么sinon不認得我的存根?

[英]Why doesn't sinon recognize my stub?

假設我有一個像這樣導出的模塊:

module.exports = mymodule;

然后在我的測試文件中,我需要該模塊並存根它。

var mymodule = require('./mymodule');

describe('Job gets sports data from API', function(){

    context('When there is a GET request', function(){
        it('will call callback after getting response', sinon.test(function(done){
            var getRequest = sinon.stub(mymodule, 'getSports');
            getRequest.yields();
            var callback = sinon.spy();
            mymodule.getSports(callback);
            sinon.assert.calledOnce(callback);
            done();
        }));
    });
});

這有效並且測試通過了! 但是如果我需要導出多個對象,一切都會崩潰。 見下文:

module.exports = {
    api: getSports,
    other: other
};

然后我嘗試調整我的測試代碼:

var mymodule = require('./mymodule');

describe('Job gets sports data from API', function(){

    context('When there is a GET request', function(){
        it('will call callback after getting response', sinon.test(function(done){
            var getRequest = sinon.stub(mymodule.api, 'getSports');
            getRequest.yields();
            var callback = sinon.spy();
            mymodule.api.getSports(callback);
            sinon.assert.calledOnce(callback);
            done();
        }));
    });
});

在這種情況下,我的測試失敗了。 如何更改存根代碼以使其正常工作? 謝謝!

基於此

module.exports = {
    api: getSports,
    other: other
};

看起來mymodule.api本身沒有getSports方法。 相反, mymodyle.api是對模塊內部的getSports函數的引用。

而不是存根getSports你需要存根api

var getRequest = sinon.stub(mymodule, 'api');

但是,考慮到您嘗試存根getSports ,您可能想要更新導出函數的方式,而不是存根它的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM