How to mock/stub a constructor

4,112 views
Skip to first unread message

Jean-Philippe Poulin de Courval

unread,
Jul 25, 2012, 11:11:58 AM7/25/12
to sin...@googlegroups.com
Hi everyone, I'm a newbie to sinonjs and I need help. I want to know, how can I mock the constructor function of an class? For example, if I have this code:

var MyObject = function() {
 // constructor
};

MyObject.prototype.aMethod = function() { ... };

How can I mock this object to replace the constructor with my own function? So, when I will create a new object by doing var aObject = new MyObject(); it will not call the real constructor but only the function I provided.

I've tried this without success:

var mock = sinon.mock(MyObject.prototype);
mock.expects('constructor').returns({ Dispose: function() {} });

And also:
var mock = sinon.mock(MyObject.prototype);
mock.expects('constructor').returns({ Dispose: function() {} });

So, how can I do that? Is it possible? What is the correct way to do something like this?
Thanks for your help!

Jean-Philippe Poulin de Courval

unread,
Jul 25, 2012, 4:10:54 PM7/25/12
to sin...@googlegroups.com
I finally found a hack for this problem. I created a new class that extends the one I want to override the constructor. My code looks like this:

var MyObject = function() {
 // constructor
};

My setup method in my test have this in:
var tmp = MyObject;
var ExtendedMyObject = function() {};
goog.inherits(ExtendedMyObject, MyObject);
MyObject = ExtendedMyObject;

And now my teardown:
MyObject = tmp;


You probably noticed that I'm using Google Closure. It provides a easy way to manage dependencies and inheritance. I was already using it in my project so I kept using it in this case.
Feel free to submit a better response to my initial problem.

Also, why SinonJs doesn't override the constructor (if it's the right name for this) of an object like this? Is there a reason?
Thank you!
Reply all
Reply to author
Forward
0 new messages