I am trying to stub a method using sinon.js but I get the following error:
Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function
I also went to this question (Stubbing and/or mocking a class in sinon.js?) and copied and pasted the code but I get the same error.
Here is my code:
Sensor = (function() {
// A simple Sensor class
// Constructor
function Sensor(pressure) {
this.pressure = pressure;
}
Sensor.prototype.sample_pressure = function() {
return this.pressure;
};
return Sensor;
})();
// Doesn't work
var stub_sens = sinon.stub(Sensor, "sample_pressure").returns(0);
// Doesn't work
var stub_sens = sinon.stub(Sensor, "sample_pressure", function() {return 0});
// Never gets this far
console.log(stub_sens.sample_pressure());
Here is the jsFiddle (http://jsfiddle.net/pebreo/wyg5f/5/) for the above code, and the jsFiddle for the SO question that I mentioned (http://jsfiddle.net/pebreo/9mK5d/1/).
I made sure to include sinon in the External Resources in jsFiddle and even jQuery 1.9. What am I doing wrong?
Thanks to @loganfsmyth for the tip. I was able to get the stub to work on an Ember class method like this:
Your code is attempting to stub a function on
Sensor
, but you have defined the function onSensor.prototype
.is essentially the same as this:
but it is smart enough to see that
Sensor["sample_pressure"]
doesn't exist.So what you would want to do is something like these:
or
or
I ran into the same error trying to mock a method of a CoffeeScript class using Sinon.
Given a class like this:
You can replace its method with a spy this way:
Just replace
spy
withstub
ormock
as needed.Note that you'll need to replace
assert.ok
with whatever assertion your testing framework has.The top answer is deprecated. You should now use:
Or for static methods:
Or for simple cases just use returns:
Or if you want to stub a method for an instance: