Reputation: 265
I have been on this for quite long and maybe I'm just missing something but my research did not yield any results that would help me.
So my question is:
If I have some code like this:
shell.on('message', function (message) {
// do something
});
And I want to test it as if it had been called with a certain message (or even an error), could I somehow do that with Sinon? ( just putting the do something in an external function will only work to some degree so I do hope for an answer that at least has a way to fake-call shell.on
to test if the inner function gets invoked).
The "shell" is an instance of the shell of the npm Package "Python-Shell"
Maybe it's not possible at all or maybe I'm just blind but any help is much appreciated!
Upvotes: 0
Views: 468
Reputation: 92440
The python-shell
instance is instance of an EventEmitter
. So you can cause the on
handler to fire by just emitting the message:
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?'
You can also stub the instance with Sinon and call yields
to call the callback:
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);
});
This might be more useful if you don't want to prevent the default behavior when running a test.
Upvotes: 2