Skip to content

Instantly share code, notes, and snippets.

@9wick
Created February 7, 2018 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 9wick/8e5651fb2c5572a355cc7f3881835b99 to your computer and use it in GitHub Desktop.
Save 9wick/8e5651fb2c5572a355cc7f3881835b99 to your computer and use it in GitHub Desktop.
Node.jsで単体testを書く際に,モジュールをstubに置き換える ref: https://qiita.com/wicket/items/af9a5d74608bedf97a85
var moduleStubs = {};
var originalJsLoader = require.extensions['.js'];
var stubOnModule = function(module) {
var path = require.resolve(module);
var stub = sinon.stub();
moduleStubs[path] = stub;
delete require.cache[path];
return stub;
};
require.extensions['.js'] = function (obj, path) {
if (moduleStubs[path])
obj.exports = moduleStubs[path];
else
return originalJsLoader(obj, path);
};
afterEach(function() {
for (var path in moduleStubs) {
delete moduleStubs[path];
}
});
it('test', function(){
stubOnModule("module");
var m = require("module"); //return stub
var instance = new m(); // OK
var value = m.b; // ok
m.a(); // error : m.a is not a function
var value = m.c.d; // error : Cannot read property 'd' of undefined
var instance2 = new m.A({}); // error : ws.Server is not a constructor
});
it('test', function(){
var stub = stubOnModule("module");
stub.a = sinon.stub();
stub.c = sinon.stub();
stub.c.d = sinon.stub();
stub.A = sinon.stub();
var m = require("module"); //return stub
m.a(); // error : m.a is not a function
var value = m.c.d; // error : Cannot read property 'd' of undefined
var instance2 = new m.A({}); // error : m.A is not a constructor
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment