【问题标题】:Sinon spy on function expressionSinon 窥探函数表达式
【发布时间】:2016-05-07 17:28:56
【问题描述】:

是否可以让 sinon 窥探函数表达式?以这段代码为例。

function one() { return 1; }
function two() { return 2; }
function three() { return 3; }

function myMethod() {
  var n1 = one();
  var n2 = two();
  var n3 = three();
  return n1 + n2 + n3;
}


QUnit.module('My test');

QUnit.test('testing functions', (assert) => {
  assert.expect(3);
  
  const spyOne = sinon.spy(one);
  const spyTwo = sinon.spy(two);
  const spyThree = sinon.spy(three);
	myMethod();

  assert.ok(spyOne.called, "called one");
  assert.ok(spyTwo.called, "called two");
  assert.ok(spyThree.called, "called three");
  
  sinon.restore();
});

即使我打电话给myMethod() 并且我在one - two - three 上有间谍,我仍然在one.called 上得到错误消息(twothree 也是如此)

我在这里错过了什么?

谢谢!

【问题讨论】:

标签: javascript unit-testing sinon function-expression


【解决方案1】:

调用sinon.spy(fn) 不会改变fn,它只是创建一个 函数(间谍),它将调用fn

为了能够测试onetwothree,您需要将这些函数(或者更确切地说,它们的引用)替换为间谍,然后再恢复它们:

// keep references to the original functions
var _one   = one;
var _two   = two;
var _three = three;

// replace the original functions with spies
one   = sinon.spy(one);
two   = sinon.spy(two);
three = sinon.spy(three);

// call our method
myMethod();

// test
assert.ok(one.called,   "called one");
assert.ok(two.called,   "called two");
assert.ok(three.called, "called three");

// restore the original functions
one   = _one;
two   = _two;
three = _three;

但这并不理想,如果可能的话,我可能会将所有函数分组到一个对象中。这样也能让诗浓自己恢复原状。

【讨论】:

  • 这只有在函数定义和测试在同一个文件中时才有效,这种情况很少发生。
  • @GovindRai 正确,但我没有为该特定问题提供解决方案。我只是在解释为什么问题中的原始代码不能按预期工作以及如何解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 2016-10-08
  • 2016-09-13
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 2017-02-27
  • 2021-01-09
相关资源
最近更新 更多