簡體   English   中英

錫諾間諜的功能表達

[英]Sinon spy on function expression

是否可以使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 - two - three仍然是假的。被one.called (對twothree相同)

我在這里想念什么?

謝謝!

調用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;

不過這並不理想,如果可能的話,我可能會將所有功能分組到一個對象中。 那也將使Sinon能夠恢復原件本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM