删除模块function
编辑:有点更精确。
我想testing我们团队创build的Github API封装扩展的用例。 对于testing,我们不想直接使用API包装器扩展,所以我们想要把它的function截掉。 所有对API封装器的调用都应该为testing而被删除,而不仅仅是创build一个复制存根。
我在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.stub(...)
一个函数模块。
有任何想法吗?
在纯Sinon中可能有一种方法可以完成这个,但是我怀疑它会很不好用。 然而, proxyquire是一个为解决这类问题而devise的节点库。
假设你想testing一些使用github模块的模块foo
; 你会写下如下的东西:
var proxyquire = require("proxyquire"); var foo = proxyquire(".foo", {"./github", myFakeGithubStub});
myFakeGithubStub
可以是任何东西; 一个完整的存根,或实际执行一些调整,等等
如果在上面的例子中, myFakeGithubStub
的属性“@global”被设置为true(即通过执行myFakeGithubStub["@global"] = true
),那么github模块将被replace为存根不仅在foo
模块本身,但在foo
模块需要的任何模块中。 但是,正如全局选项的代理文档中所述 ,一般来说,这个特性是unit testingdevise不佳的标志,应该避免。
我发现这对我有效…
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 eg '/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!'
最简单的解决scheme是重构你的模块:
而不是这个:
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!!"); });