javascript - 存根和/或监视可选的全局函数:Sinon、mocha 和 chai
问题描述
我有一个方法可以检查是否定义了全局函数(它可能可用也可能不可用,取决于每个客户的请求)。如果已定义,它将使用适当的数据调用它。如果没有,它将默默地失败。这是期望的行为。
我想做的是测试它。有没有一种方法可以模拟和/或监视,libFunction
以便我可以确保使用正确的数据调用它一次(这里的函数非常简化,在此过程中会发生一些数据处理)。
这是有问题的方法:
function sendData(data) {
let exists;
try {
// eslint-disable-next-line no-undef
if (libFunction) exists = true;
} catch (e) {
exists = false;
}
if (exists) {
// eslint-disable-next-line no-undef
libFunction(data);
}
}
我已经尝试libFunction
在我的测试中进行定义,然后将其存根,但这并没有达到我想要的效果:
describe('sendEvent', function () {
function libFunction(data) {
console.log('hi', data);
}
it('should call libFunction once', function () {
var stub = sinon.stub(libFunction);
var data = "testing";
sendEvent(data);
expect(stub.called).to.be.true;
});
});
但是,此测试未通过:AssertionError: expected undefined to be true
我用间谍尝试过类似的事情:
describe('sendEvent', function () {
function libFunction(data) {
console.log('hi', data);
}
it('should call libFunction once', function () {
var spy = sinon.spy(libFunction);
var data = "testing";
sendEvent(data);
expect(spy.called).to.be.true;
});
});
这也失败了:AssertionError: expected false to be true
有没有办法做到这一点?
解决方案
FWIW,我在尝试解决在 Node.js 中存根全局方法的问题时遇到了这个问题。就我而言,这有效(我的示例使用Sinon.sandbox
,但“常规”Sinon.spy
也应该有效):
const encodeSpy = sandbox.spy(global, "encodeURIComponent");
// later...
Sinon.assert.calledWith(encodeSpy, {expectedParamValue});
推荐阅读
- javascript - 从 js 对象中删除数据
- python-3.x - 在执行 box-cox 和分解之后,想要根据状态找到预测
- c++ - 在现代 CMake 中定义预处理器
- vba - 如何在 Word 2016 中触发鼠标右键单击事件处理程序?
- reactjs - 从反应导航中动态删除一个drawerItem
- bash - 通过 shell 的 Oracle 数据库连接
- oracle - 如何在顶点5创建树形图?
- testing - 自动化服务器运行的 Testcafe 测试随机失败
- c# - 无法加载文件或程序集“ClearScriptV8-32.DLL”或其依赖项之一。指定的模块无法找到
- spring-boot - 需要在 POST 端点中模拟服务方法,跳过 @RequestBody 注释