If I have a module that exports a single class, how can I mock/stub it with proxyquire
?
Currently I have the following, which seems to work, but is rather lengthy and doesn't make proper use of proxyquire
:
some-class.js
var SomeClass = function(){
console.log("constructed SomeClass");
}
SomeClass.prototype.shout = function(){
console.log("HELLO!");
}
module.exports = SomeClass;
my-module.js
var SomeClass = require('some-class');
module.exports.doSomething = function(){
var a = new SomeClass();
a.shout();
}
test-my-module.js
// :::: bit I'd like to avoid ::::::
var cls = require('some-class');
var SomeClassStub = function(){
cls.apply(this, arguments);
};
SomeClassStub.prototype = Object.create(originalCls.prototype);
// :::::::::::::::::::::::::::::::::
var myModule = proxyquire('my-module', {
'some-class': SomeClassStub
});
SomeClassStub.prototype.shout = function(){
console.log("whisper");
}
myModule.doSomething();
Note that I am fairly new to mocking (and testing!) so I might be missing something obvious, but I was hoping that proxyquire
would deal with my problem itself (rather than me needing to use another library or write the above code).