javascript - 在 Sinon 中假调用具有特定参数的函数
问题描述
我已经研究了很长时间,也许我只是错过了一些东西,但我的研究并没有产生任何对我有帮助的结果。
所以我的问题是:
如果我有这样的代码:
shell.on('message', function (message) {
// do something
});
而且我想测试它,就好像它被某个消息(甚至是错误)调用一样,我可以用诗乃以某种方式做到这一点吗?(只是将做某事放在外部函数中只会在某种程度上起作用,所以我确实希望得到一个答案,至少有一种方法可以假调用shell.on
来测试内部函数是否被调用)。
“shell”是 npm 包“Python-Shell”的 shell 的一个实例
也许根本不可能,或者我只是瞎了眼,但非常感谢任何帮助!
解决方案
该python-shell
实例是 的实例EventEmitter
。因此,您可以on
通过发出消息来触发处理程序:
var PythonShell = require('python-shell');
var pyshell = new PythonShell('my_script.py');
pyshell.on('message', function (message) {
console.log("recieved", message);
});
pyshell.emit('message', "fake message?")
// writes: 'recieved fake message?'
您还可以使用 Sinon 存根实例并调用yields
回调:
const sinon = require('sinon')
var PythonShell = require('python-shell');
var pyshell = new PythonShell('my_script.py');
var stub = sinon.stub(pyshell, "on");
stub.yields("test message")
// writes received test message to console
pyshell.on('message', function (message) {
console.log("received", message);
});
如果您不想在运行测试时阻止默认行为,这可能会更有用。
推荐阅读
- android - Android kotlin 两种方式数据绑定问题
- node.js - 克隆到另一台 PC 后 Angular 无法正常工作
- javascript - JQuery onChange 使用更改前的值(需要更改后的值)
- r - 在R中的数据框中使用条件对日期数据进行分组
- c++ - 由于 PC 显示设置的更改,Qt Widget 被部分裁剪
- apache-kafka - 在本地主机上设置 Kafka 的问题
- postgresql - Postgresql 嵌套函数
- android - 尝试使用 Facebook 登录凭据登录 Firebase 时出错
- linux - 阿帕奇配置 2.4
- typescript - 使用 Angular 6 的动态选项卡