用Sinon.js拼写一个类方法

问题描述 投票:79回答:4

我试图使用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/)。

我确保在jsFiddle甚至jQuery 1.9的外部资源中包含sinon。我究竟做错了什么?

javascript node.js sinon
4个回答
140
投票

您的代码试图在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());

34
投票

最常见的答案已被弃用。你现在应该使用:

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({})

3
投票

我试图使用Sinon模拟CoffeeScript类的方法时遇到了同样的错误。

鉴于这样的类:

class MyClass
  myMethod: ->
    # do stuff ...

你可以用这种方式用间谍替换它的方法:

mySpy = sinon.spy(MyClass.prototype, "myMethod")

# ...

assert.ok(mySpy.called)

只需根据需要用spystub替换mock

请注意,您需要将assert.ok替换为您的测试框架所具有的任何断言。


2
投票

感谢@loganfsmyth的提示。我能够让存根工作在这样的Ember类方法:

sinon.stub(Foo.prototype.constructor, 'find').returns([foo, foo]);
expect(Foo.find()).to.have.length(2)
© www.soinside.com 2019 - 2024. All rights reserved.