1. ホーム
  2. javascript

[解決済み] Sinon.jsでクラスメソッドをスタブする

2022-09-24 11:07:03

質問

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/ )です。また、上記のコードのjsFiddleと、私が言及したSOの質問のjsFiddle( http://jsfiddle.net/pebreo/9mK5d/1/ ).

私は、シノンを必ず 外部リソース を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());