Created
February 7, 2018 02:54
-
-
Save 9wick/8e5651fb2c5572a355cc7f3881835b99 to your computer and use it in GitHub Desktop.
Node.jsで単体testを書く際に,モジュールをstubに置き換える ref: https://qiita.com/wicket/items/af9a5d74608bedf97a85
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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