一尘不染

使用Sinon.js存根类方法

node.js

我正在尝试使用sinon.js存根方法,但是出现以下错误:

Uncaught TypeError: Attempted to wrap undefined property sample_pressure as function

这是我的代码:

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/)。

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


阅读 312

收藏
2020-07-07

共1个答案

一尘不染

您的代码正在尝试在一个函数上存根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());
2020-07-07