簡體   English   中英

存根模塊功能

[英]Stub out module function

編輯:更准確一點。

我想為我們團隊創建的Github API包裝器擴展測試用例。 對於測試,我們不希望直接使用API​​包裝器擴展,因此我們希望將其功能存根。 所有對API包裝器的調用都應該被刪除以進行測試,而不僅僅是創建克隆存根。

我在Node.js中有一個模塊“github”:

module.exports = function(args, done) {
    ...
}

而我要求這樣:

var github = require('../services/github');

現在,我想使用Sinon.js刪除github(...)

var stub_github = sinon.stub(???, "github", function (args, callback) { 
    console.log("the github(...) call was stubbed out!!");
});

sinon.stub(...)希望我傳遞一個對象和一個方法,並且不允許我刪除一個函數模塊。

有任何想法嗎?

可能有一種方法可以在純Sinon中實現這一點,但我懷疑它會非常hacky。 但是, proxyquire是一個旨在解決這類問題的節點庫。

假設您要測試一些使用github模塊的模塊foo ; 你會寫一些類似的東西:

var proxyquire = require("proxyquire");
var foo = proxyquire(".foo", {"./github", myFakeGithubStub});

myFakeGithubStub可以是任何東西; 一個完整的存根,或實際的實現與一些調整等。

如果,在上面的例子中, myFakeGithubStub將屬性“@global”設置為true,(即通過執行myFakeGithubStub["@global"] = true ),那么github模塊將不僅僅在foo模塊本身中被存根替換,但在foo模塊需要的任何模塊中。 但是,正如關於全局選項proxyquire文檔中所述 ,一般來說,此功能是設計不良的單元測試的標志,應該避免。

我發現這對我有用......

const sinon          = require( 'sinon' );
const moduleFunction = require( 'moduleFunction' );

//    Required modules get added require.cache. 
//    The property name of the object containing the module in require.cache is 
//    the fully qualified path of the module e.g. '/Users/Bill/project/node_modules/moduleFunction/index.js'
//    You can get the fully qualified path of a module from require.resolve
//    The reference to the module itself is the exports property

const stubbedModule = sinon.stub( require.cache[ require.resolve( 'moduleFunction' ) ], 'exports', () => {

    //    this function will replace the module

    return 'I\'m stubbed!';
});

// sidenote - stubbedModule.default references the original module...

您必須確保在其他地方需要之前存根模塊(如上所述)...

// elsewhere...

const moduleFunction = require( 'moduleFunction' ); 

moduleFunction();    // returns 'I'm stubbed!'

最簡單的解決方案是重構您的模塊:

而不是這個:

module.exports = function(args, done) {
    ...
}

做這個:

module.exports = function(){
    return module.exports.github.apply(this, arguments);
};
module.exports.github = github;

function github(args, done) {
    ...
}

現在你需要它:

const github = require('../services/github.js');
//or
const github = require('../services/github.js').github;

存根:

const github = require('../services/github.js');
let githubStub = sinon.stub(github, 'github', function () {
    ... 
});

如果你在做

var github = require('../services/github');

在全局范圍內,那么你可以使用'global'作為對象,'github'作為被刪除的方法。

var stub_github = sinon.stub(global, "github", function (args, callback) { 
    console.log("the github(...) call was stubbed out!!");
});

暫無
暫無

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

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