簡體   English   中英

使用Sinon.js存根類方法

[英]Stubbing a class method with Sinon.js

我正在嘗試使用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());

要么

// 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());

最佳答案已棄用。 您現在應該使用:

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

我在嘗試使用Sinon模擬CoffeeScript類的方法時遇到了相同的錯誤。

給定這樣的課程:

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

您可以通過以下方式將其方法替換為間諜:

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

# ...

assert.ok(mySpy.called)

只需根據需要用stubmock代替spy

請注意,您需要用測試框架具有的任何斷言替換assert.ok

感謝@loganfsmyth的提示。 我能夠使存根在Ember類方法上工作,如下所示:

sinon.stub(Foo.prototype.constructor, 'find').returns([foo, foo]);
expect(Foo.find()).to.have.length(2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM