如何在调用时从spy.on(obj,'funcName')返回伪数据?

时间:2016-03-05 09:55:30

标签: javascript node.js unit-testing mocha chai

我不知道有没有任何功能! 请告诉我有可能吗?

类似的东西:

spy(obj, 'funcName').and.returnValue(5); // spy will return a fake data when 'funcName'called.

我正在使用mochachai-spies

2 个答案:

答案 0 :(得分:1)

而不是间谍,请看一下使用存根。

根据文档:

  

测试存根是具有预编程行为的功能(间谍)。除了可用于改变存根行为的方法之外,它们还支持完整的测试间谍API。

Stubs有一个“返回”方法来做你正在寻找的东西。

var stub = sinon.stub();

stub.returns(54)

stub(); // 54

答案 1 :(得分:0)

看起来他们添加了init: function() { var thisDropzone = this; track = getParameterByName('trackno'); $.getJSON('get_upload_files.php?track='+track, function(data) { // get the json response $.each(data, function(key,value){ //loop through it var mockFile = { name: value.name, size: value.size }; // here we get the file name and size as response thisDropzone.options.thumbnail.call(thisDropzone, mockFile, "uploads/"+value.name);//uploadsfolder is the folder where you have all those uploaded files thisDropzone.emit("addedfile", mockFile); }); // update maxFiles thisDropzone.options.maxFiles = 10 - data.length; }); } 函数来做到这一点,但API对我来说似乎有点奇怪。我安装了lastest code from their master branch并做了一些游戏。以下是我的实验:

chai.spy.returns

运行这些测试的输出是:

var chai = require('chai'),
    spies = require('chai-spies');

chai.use(spies);
var expect = chai.expect;
var obj = null;

describe('funcName', function() {

  beforeEach(function() {
    obj = {
      funcName: function() {
        return true;
      }
    }
  });

  // PASSES
  it('returns true by default', function() {
    expect(obj.funcName()).to.be.true
  });

  // PASSES
  it('returns false after being set to a spy', function() {
    var spyFunction = chai.spy.returns(false);
    obj.funcName = spyFunction;
    expect(obj.funcName()).to.be.false
  });

  // FAILS
  it('returns false after being altered by a spy', function() {
    chai.spy.on(obj, 'funcName').returns(false);
    expect(obj.funcName()).to.be.false
  });

});

因此,他们希望您使用返回值实例化间谍对象,然后用funcName ✓ returns true by default ✓ returns false after being set to a spy 1) returns false after being altered by a spy 2 passing (14ms) 1 failing 1) funcName returns false after being altered by a spy: TypeError: Object #<Object> has no method 'returns' at Context.<anonymous> (test.js:31:34) 替换funcName上的obj函数。你无法窥探一个函数并一举设置它的返回值。

此外,该功能已添加到October, 2015中,并且从那时起它们尚未发布新版本。我的建议是使用更成熟的库Sinon.js来进行间谍和存根。您可以使用他们的Stub API来更改函数的返回值:

sinon.stub(obj, 'funcName').returns(5);

Stub API提供了许多方法来改变函数的行为,甚至可以让你用完全自定义的函数替换它:

var func = function() {...}

sinon.stub(obj, 'funcName', func);