gpt4 book ai didi

javascript - 西农(Sinon)监视函数表达式

转载 作者:行者123 更新时间:2023-11-28 18:35:56 24 4
gpt4 key购买 nike

是否可以让 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() 并且我有 spy 监视 one - 二 - Three 我仍然在 one.known 上得到错误( 相同)

我在这里缺少什么?

谢谢!

最佳答案

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

为了能够测试 onetwo Three,您需要替换这些函数(或者更确切地说,替换它们的引用)与 spy ,然后恢复他们:

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

但这并不理想,如果可能的话,我可能会将所有函数分组到一个对象中。这样一来,诗乃也能恢复原来的样子了。

关于javascript - 西农(Sinon)监视函数表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com