[英]Sinon spy on function expression
is it possible to make sinon spy on function expressions? 是否可以使sinon监视函数表达式? Look this code for example.
例如看下面的代码。
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(); });
Even though I call myMethod()
and I have spies on one - two - three
I still get false on one.called
(same for two
and three
) 即使我调用
myMethod()
并且对one - two - three
有间谍,但对one - two - three
仍然是假的。被one.called
(对two
和three
相同)
What am I missing here? 我在这里想念什么?
Thanks! 谢谢!
Calling sinon.spy(fn)
doesn't change fn
, it merely creates a new function (the spy) that will call fn
. 调用
sinon.spy(fn)
不会更改fn
,它只是创建一个将调用fn
的新函数(间谍)。
For you to be able to test one
, two
, three
, you need to replace those functions (or rather, their references) with spies, and restore them afterwards: 为了能够测试
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;
It's not ideal though, and if possible I would probably group all the functions into an object. 不过这并不理想,如果可能的话,我可能会将所有功能分组到一个对象中。 That would also enable Sinon to restore the originals itself.
那也将使Sinon能够恢复原件本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.