2016-05-07 6 views
0

sinon spyを関数式にすることは可能ですか?例えば、このコードを見てください。Sinon spy on関数式

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); 
 
\t myMethod(); 
 

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

私はmyMethod()を呼び出して、私はまだ(twothreeに同じ)one.called上の偽取得one - two - threeにスパイを持っているにもかかわらず

私はここで何をしないのですか?

ありがとうございます! fnを変更しないsinon.spy(fn)を呼び出す

+0

[関数呼び出しの検証とサイロンスパイを使用した引数の検査]の可能な複製(https://stackoverflow.com/questions/29800733/verifying-function-call-and-inspecting-arguments-using-sinon-spies) –

答えて

3

が、それは単にfnを呼び出します新しい機能(スパイ)を作成します。 、あなたはスパイでそれらの機能(またはむしろ、その参照)を交換し、その後それらを復元するためにあなたがoneをテストできるようにするには

twothree必要があります。

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

それはしかし理想的ではないですが、可能であれば、私はおそらくすべての関数をオブジェクトにグループ化します。そうすれば、シノンはオリジナルを元に戻すことができます。