在 Sinon 中假调用具有特定参数的函数
Fake calling of a function with specific arguments in Sinon
我已经研究这个很长时间了,也许我只是遗漏了一些东西,但我的研究没有产生任何对我有帮助的结果。
所以我的问题是:
如果我有这样的代码:
shell.on('message', function (message) {
// do something
});
而且我想测试它,就好像它是用特定消息(甚至是错误)调用的一样,我可以用 Sinon 以某种方式做到这一点吗? (只是将 do something 放在外部函数中只会在某种程度上起作用,所以我希望得到一个答案,至少有一种方法可以假调用 shell.on
来测试内部函数是否被调用)。
"shell" 是 npm 包 shell 的实例 "Python-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);
});
如果您不想阻止 运行 测试时的默认行为,这可能会更有用。
我已经研究这个很长时间了,也许我只是遗漏了一些东西,但我的研究没有产生任何对我有帮助的结果。
所以我的问题是:
如果我有这样的代码:
shell.on('message', function (message) {
// do something
});
而且我想测试它,就好像它是用特定消息(甚至是错误)调用的一样,我可以用 Sinon 以某种方式做到这一点吗? (只是将 do something 放在外部函数中只会在某种程度上起作用,所以我希望得到一个答案,至少有一种方法可以假调用 shell.on
来测试内部函数是否被调用)。
"shell" 是 npm 包 shell 的实例 "Python-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);
});
如果您不想阻止 运行 测试时的默认行为,这可能会更有用。