gpt4 book ai didi

javascript - Sinon spy 函数被调用但未被跟踪

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:19 25 4
gpt4 key购买 nike

我正在使用 Mocha 和 sinon 来监视函数调用。该函数被正确调用,但 spy 没有跟踪它。

这是我正在测试的模块

export default (() => {

function test1(){
console.log('called second func');
return 5;
}

function callThis(){
console.log('called first func');
test1();
}

return {
test1,
callThis
};

})();

这是测试

import Common from './common';

describe('spy test', () => {
var setSpy = sinon.spy(Common, 'test1');

Common.callThis();

var result = setSpy.called;

it(`does the test`, () => {
expect(result).to.equal(true);
});

});

我基本上是在调用第一个函数,但想检查是否调用了第二个函数。控制台日志告诉我这正在发生,但是 spy 返回 false 并且没有注意到它正在监视的东西。我错过了什么吗?

最佳答案

当您调用 sinon.spy(Common, 'test1'); 时,您正在修改 Common 对象上的 test1 字段以替换它与 spy 。但是,您在 common.js 中的代码正在调用 test1 直接 而不是调用 test1 您的模块导出的对象。 因此,当您执行 Common.callThis() 时, spy 不会被触及,您会得到您观察到的错误。

这是一个修改后的 common.js 文件,可以让您的测试通过:

export default (() => {

var obj = {};

obj.test1 = function test1(){
console.log('called second func');
return 5;
}

obj.callThis = function callThis(){
console.log('called first func');
// This calls `test1` through `obj` instead of calling it directly.
obj.test1();
}

return obj;
})();

关于javascript - Sinon spy 函数被调用但未被跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45732572/

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