我正在尝试使用sinon.js存根方法,但是我收到以下错误:
Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function
我也回答了这个问题(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/)。
我确保将sinon包含在jsFiddle中的外部资源甚至jQuery 1.9中。我做错了什么?
答案 0 :(得分:135)
您的代码正在尝试在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());
答案 1 :(得分:33)
最常见的答案已被弃用。你现在应该使用:
sinon.stub(YourClass.prototype, 'myMethod').callsFake(() => {
return {}
})
或者对于静态方法:
sinon.stub(YourClass, 'myStaticMethod').callsFake(() => {
return {}
})
或者对于简单的情况,只需使用return:
sinon.stub(YourClass.prototype, 'myMethod').returns({})
sinon.stub(YourClass, 'myStaticMethod').returns({})
或者,如果您想为实例存根方法:
const yourClassInstance = new YourClass();
sinon.stub(yourClassInstance, 'myMethod').returns({})
答案 2 :(得分:3)
尝试使用Sinon模拟CoffeeScript类的方法时遇到了同样的错误。
鉴于这样的课程:
class MyClass
myMethod: ->
# do stuff ...
你可以用这种方式用间谍替换它的方法:
mySpy = sinon.spy(MyClass.prototype, "myMethod")
# ...
assert.ok(mySpy.called)
只需根据需要将spy
替换为stub
或mock
。
请注意,您需要将assert.ok
替换为您的测试框架所具有的任何断言。
答案 3 :(得分:2)
感谢@loganfsmyth的提示。我能够使用存根来处理这样的Ember类方法:
sinon.stub(Foo.prototype.constructor, 'find').returns([foo, foo]);
expect(Foo.find()).to.have.length(2)