I'm using Jasmine to write my tests, but I guess I'd have this problem with any other testing framework. Let's say that we have a module foo
with two functions, Bar
and Baz
, which are constructors (but could be just normal functions):
var Bar = exports.Bar = function Bar() {
this.baz = new Baz();
};
var Baz = exports.Baz = function Baz() {
};
Now I would like to test Bar
, but with a fake Baz
implementation:
var foo = require('foo');
describe("foo.Bar", function() {
it("initializes its own Baz", function() {
spyOn(foo, 'Baz'); // this replaces foo.Baz with a fake implementation
var bar = new foo.Bar();
expect(foo.Baz).toHaveBeenCalled();
});
});
The problem is that this test will fail, because Bar
instantiates a new Baz
using the variable Baz
, which cannot be changed from outside. The only thing that got swapped by using spyOn()
is exports.Baz
.
The obvious solution is to write this.baz = new exports.Baz();
but it kind of feels awkward. If I have more functions which I want to use inside my module, I would have to always call all of them using the exports.
prefix. Is there any other approach here?