用Sinon.js拼写一个类方法 [英] Stubbing a class method with Sinon.js

查看:299
本文介绍了用Sinon.js拼写一个类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to stub a method using sinon.js but I get the following error:

未捕获的TypeError:尝试包装未定义的属性sample_pressure as function

我也回答了这个问题(在sinon.js中绑定和/或模拟一个类?并复制并粘贴代码但我得到了同样的错误。

I also went to this question (Stubbing and/or mocking a class in sinon.js?) and copied and pasted the code but I get the same error.

这是我的代码:

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

Here is the jsFiddle (http://jsfiddle.net/pebreo/wyg5f/5/) for the above code, and the jsFiddle for the SO question that I mentioned (http://jsfiddle.net/pebreo/9mK5d/1/).

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

I made sure to include sinon in the External Resources in jsFiddle and even jQuery 1.9. What am I doing wrong?

推荐答案

您的代码正在尝试在传感器上存根函数,但您已在 Sensor.prototype 上定义了该功能。

Your code is attempting to stub a function on Sensor, but you have defined the function on Sensor.prototype.

sinon.stub(Sensor, "sample_pressure", function() {return 0})

基本上与此相同:

Sensor["sample_pressure"] = function() {return 0};

但它足够聪明,可以看到传感器[sample_pressure] 不存在。

but it is smart enough to see that Sensor["sample_pressure"] doesn't exist.

所以你想要做的是这样的事情:

So what you would want to do is something like these:

// 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.js拼写一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆