I'm writing a server-side application with node.js and would like to include unit tests. One thing I'm struggling with is a good way to unit test EventEmitter
and setInterval/setTimout
What options do I have to unit test asynchronous server side javascript?
I'm aware I can just attach another listener to the EventEmitter that is the testing function but then how do I garantuee that the testing function ever runs? part of the unit test is to ensure every part of the unit test runs.
I could use setTimeout myself but that seems like a hackish solution.
If it helps here is some exampler code I'm trying to test.
...
function init(param) {
...
// run update entities periodically
setInterval(this._updateEntities.bind(this, param.containerFull),
1000 / param.fps);
...
}
...
EntityUpdater.prototype = {
...
"_updateEntities": function updateEntitiesfunc(fn) {
this._tickEmitter.emit(
"tick",
new dataContainer.DataContainer(this.getEntityCount())
.on(
"full", fn.bind(this)
)
);
},
...
}
...
(emit will trigger a event)
[Edit]
I started reading some of the EvevntEmitter tests at https://github.com/ry/node/tree/master/test/simple and it helps me see how to go about this.
I would recommend you check out Jasmine for your tests. It's built to run tests outside a browser environment, and it stubs calls such as setTimeout
, providing you with a fake clock with which you can move time forward at your leisure for testing anything time-related.
Personally what helped me the most was reading the tests for node.js themselves (I only read about half of them).
That gave me a good feeling of how to test the asynchronous code.
Thanks to @tmdean for pointing out another example of how to test async code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With