Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 调用spy.on(obj,';funcName';)时如何从中返回假数据?_Javascript_Node.js_Unit Testing_Mocha.js_Chai - Fatal编程技术网

Javascript 调用spy.on(obj,';funcName';)时如何从中返回假数据?

Javascript 调用spy.on(obj,';funcName';)时如何从中返回假数据?,javascript,node.js,unit-testing,mocha.js,chai,Javascript,Node.js,Unit Testing,Mocha.js,Chai,我不知道有没有什么功能! 请让我知道有可能吗 诸如此类: spy(obj, 'funcName').and.returnValue(5); // spy will return a fake data when 'funcName'called. 我正在使用mocha,chai-spies看起来他们添加了chai.spy.returns函数来实现这一点,但API对我来说似乎有点奇怪。我安装了电脑,做了一些游戏。以下是我的实验: var chai = require('chai'), s

我不知道有没有什么功能! 请让我知道有可能吗

诸如此类:

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

我正在使用
mocha
chai-spies

看起来他们添加了
chai.spy.returns
函数来实现这一点,但API对我来说似乎有点奇怪。我安装了电脑,做了一些游戏。以下是我的实验:

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)
存根API提供了更多改变函数行为的方法,甚至允许您用完全自定义的函数替换它:

sinon.stub(obj, 'funcName').returns(5);
var func = function() {...}

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

与其说是间谍,不如说是使用存根

根据文件:

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

存根有一个“returns”方法来完成您要查找的内容

var stub = sinon.stub();

stub.returns(54)

stub(); // 54