0

是否可以让 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(与twoand相同three

我在这里想念什么?

谢谢!

4

1 回答 1

3

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

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

// 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;

但这并不理想,如果可能的话,我可能会将所有功能分组到一个对象中。这样一来,诗乃也可以自己恢复原件。

于 2016-05-07T19:50:10.753 回答