简体   繁体   中英

Unit testing event driven javascript

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM