mit*_*man 10 javascript node.js sinon
编辑:更准确一点.
我想为我们团队创建的Github API包装器扩展测试用例.对于测试,我们不希望直接使用API包装器扩展,因此我们希望将其功能存根.所有对API包装器的调用都应该被删除以进行测试,而不仅仅是创建克隆存根.
我在Node.js中有一个模块"github":
module.exports = function(args, done) {
...
}
Run Code Online (Sandbox Code Playgroud)
而我要求这样:
var github = require('../services/github');
Run Code Online (Sandbox Code Playgroud)
现在,我想github(...)使用Sinon.js 存根:
var stub_github = sinon.stub(???, "github", function (args, callback) {
console.log("the github(...) call was stubbed out!!");
});
Run Code Online (Sandbox Code Playgroud)
但是sinon.stub(...)我希望传递一个对象和一个方法,并且不允许我存根一个函数模块.
有任何想法吗?
可能有一种方法可以在纯Sinon中实现这一点,但我怀疑它会非常hacky.但是,proxyquire是一个旨在解决这类问题的节点库.
假设您要测试一些foo使用github模块的模块; 你会写一些类似的东西:
var proxyquire = require("proxyquire");
var foo = proxyquire(".foo", {"./github", myFakeGithubStub});
Run Code Online (Sandbox Code Playgroud)
哪里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...
Run Code Online (Sandbox Code Playgroud)
您必须确保在其他地方需要之前存根模块(如上所述)...
// elsewhere...
const moduleFunction = require( 'moduleFunction' );
moduleFunction(); // returns 'I'm stubbed!'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14926 次 |
| 最近记录: |