您的代码正在尝试在一个函数上存根Sensor
,但是您已在上定义了该函数Sensor.prototype
。
sinon.stub(Sensor, "sample_pressure", function() {return 0})
基本上与此相同:
Sensor["sample_pressure"] = function() {return 0};
但是足够聪明地看到它Sensor["sample_pressure"]
不存在。
因此,您想要做的是这样的事情:
// Stub the prototype's function so that there is a spy on any new instance
// of Sensor that is created. Kind of overkill.
sinon.stub(Sensor.prototype, "sample_pressure").returns(0);
var sensor = new Sensor();
console.log(sensor.sample_pressure());
要么
// Stub the function on a single instance of 'Sensor'.
var sensor = new Sensor();
sinon.stub(sensor, "sample_pressure").returns(0);
console.log(sensor.sample_pressure());
要么
// Create a whole fake instance of 'Sensor' with none of the class's logic.
var sensor = sinon.createStubInstance(Sensor);
console.log(sensor.sample_pressure());