javascript – 用Sinon.js绑定一个类方法
作者:互联网
我试图使用sinon.js存根方法但我收到以下错误:
未捕获的TypeError:尝试将未定义的属性sample_pressure包装为函数
我也去了这个问题(Stubbing and/or mocking a class in sinon.js?)并复制并粘贴了代码,但我得到了同样的错误.
这是我的代码:
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());
这是上面代码的jsFiddle(http://jsfiddle.net/pebreo/wyg5f/5/),以及我提到的SO问题的jsFiddle(http://jsfiddle.net/pebreo/9mK5d/1/).
我确保在jsFiddle甚至jQuery 1.9的外部资源中包含sinon.我究竟做错了什么?
解决方法:
您的代码正在尝试在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());
标签:javascript,node-js,sinon 来源: https://codeday.me/bug/20190918/1811577.html