用 Sinon 存根类方法.js

2022-08-30 05:17:14

我正在尝试使用sinon存根方法.js但我得到以下错误:

Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function

我也去了这个问题(Stubbing和/或嘲笑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的外部资源中。我做错了什么?


答案 1

您的代码正在尝试在 上存根函数,但您已经在 上定义了该函数。SensorSensor.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());

答案 2

顶部答案已弃用。您现在应该使用:

sinon.stub(YourClass.prototype, 'myMethod').callsFake(() => {
    return {}
})

或者对于静态方法:

sinon.stub(YourClass, 'myStaticMethod').callsFake(() => {
    return {}
})

或者对于简单的情况,只需使用返回值:

sinon.stub(YourClass.prototype, 'myMethod').returns({})

sinon.stub(YourClass, 'myStaticMethod').returns({})

或者,如果要为实例存根方法:

const yourClassInstance = new YourClass();
sinon.stub(yourClassInstance, 'myMethod').returns({})