I'm very new to Chai testing. I can't find good example. Basically, what I want to happen is check wether the event got triggered.
on my patientInfo.js, the code to trigger the event is
import PatientBus from 'backbone.radio';
patientAdded() {
PatientBus.trigger('patient:added');
},
then on my patientEvents.js
import PatientBus from 'backbone.radio';
this.listenTo(PatientBus, 'patient:added', this.onPatientAdded);
onPatientAdded: function onPatientAdded() {
// blah blah blah
}
Forgot to say, I'm using Marionette radio. The event handler codes above are working great. Now, I want a chai test which will check if the listener of the event received the trigger or broadcast request. I'm not sure where to start and how I will write it.
As @Sgni mentioned, you'll need to spy on your function to 1) know whether or not it was called, and 2) inspect its return value. The Sinon syntax for doing this is:
sinon.spy(yourObject, 'onPatientAdded');
To give you some intuition for how this works, the Sinon docs list this as an example:
function once(fn) {
var returnValue, called = false;
return function () {
if (!called) {
called = true;
returnValue = fn.apply(this, arguments);
}
return returnValue;
};
}
As you can see, it wraps your original function in a closure, which keeps references to your original function's return value, and whether the function was called.
Sinon-Chai just gives you nice syntax, so you can make readable assertions like the following:
expect(yourObject.onPatientAdded).to.have.been.calledOnce;
expect(yourObject.onPatientAdded).to.have.returned(something);
So yes, there is seemingly a lot of magic, but the magic comes from Sinon's use of JavaScript closures and Sinon-Chai's clever use of object properties.