首页 > 解决方案 > 在 Sinon 中假调用具有特定参数的函数

问题描述

我已经研究了很长时间,也许我只是错过了一些东西,但我的研究并没有产生任何对我有帮助的结果。

所以我的问题是:

如果我有这样的代码:

shell.on('message', function (message) {
// do something
});

而且我想测试它,就好像它被某个消息(甚至是错误)调用一样,我可以用诗乃以某种方式做到这一点吗?(只是将做某事放在外部函数中只会在某种程度上起作用,所以我确实希望得到一个答案,至少有一种方法可以假调用shell.on来测试内部函数是否被调用)。

“shell”是 npm 包“Python-Shell”的 shell 的一个实例

也许根本不可能,或者我只是瞎了眼,但非常感谢任何帮助!

标签: javascriptunit-testingmocha.jssinon

解决方案


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);
});

如果您不想在运行测试时阻止默认行为,这可能会更有用。


推荐阅读