Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Sinon监视函数表达式_Javascript_Unit Testing_Sinon_Function Expression - Fatal编程技术网

Javascript Sinon监视函数表达式

Javascript Sinon监视函数表达式,javascript,unit-testing,sinon,function-expression,Javascript,Unit Testing,Sinon,Function Expression,有可能让sinon监视函数表达式吗?以这段代码为例 function one(){return 1;} 函数二(){return 2;} 函数三(){return 3;} 函数myMethod(){ var n1=1(); var n2=2(); var n3=3(); 返回n1+n2+n3; } 质量模块(“我的测试”); 测试('测试函数',(断言)=>{ 断言、期望(3); 常数间谍=中国间谍(一); const spyTwo=sinon.spy(两个); const spyThree=

有可能让sinon监视函数表达式吗?以这段代码为例

function one(){return 1;}
函数二(){return 2;}
函数三(){return 3;}
函数myMethod(){
var n1=1();
var n2=2();
var n3=3();
返回n1+n2+n3;
}
质量模块(“我的测试”);
测试('测试函数',(断言)=>{
断言、期望(3);
常数间谍=中国间谍(一);
const spyTwo=sinon.spy(两个);
const spyThree=sinon.spy(三个);
myMethod();
assert.ok(spyOne.called,“called one”);
assert.ok(spyTwo.called,“called two”);
assert.ok(spyThree.called,“called three”);
sinon.restore();
});
调用
sinon.spy(fn)
不会改变
fn
,它只会创建一个调用
fn
的新函数(spy)

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

// 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能够自行恢复原始文件。

调用
Sinon.spy(fn)
不会改变
fn
,它只会创建一个新函数(spy),该函数将调用
fn

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

// 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能够恢复原始版本。

只有在同一个文件中有函数定义和测试时,此版本的可能副本才起作用,这种情况很少发生。@GovindRai是正确的,但我不会为该特定问题提供解决方案。我只是解释为什么问题中的原始代码不能像预期的那样工作,以及如何解决这个问题。只有在同一个文件中有函数定义和测试时,这才有效,这种情况很少发生。@GovindRai是正确的,但我没有为这个特定问题提供解决方案。我只是解释为什么问题中的原始代码不能按预期工作,以及如何解决这个问题。