我正在尝试使用 sinon.js 存根方法,但出现以下错误:
Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function
我也去了这个问题(在 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/).
我确保将 sinon 包含在外部资源在 jsFiddle 甚至 jQuery 1.9 中。我究竟做错了什么?
您的代码正在尝试对函数进行存根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());
or
// 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());
or
// Create a whole fake instance of 'Sensor' with none of the class's logic.
var sensor = sinon.createStubInstance(Sensor);
console.log(sensor.sample_pressure());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)