简体   繁体   中英

how to capture and test for socket.io events in casper.js

I'm using Casperjs to test a socket.io application. I want the ability to assert that different emits have happened, from the server and the client, but the code I have below keeps giving me errors.

I have the following line in my test setup:

casper.page.injectJs('test_include.js');

test_include.js looks like:

document.emits = [];
document.ons = [];
(function(){
    var _origEmit = main_socket.emit;
    main_socket.emit = function(){
        console.log("SENT", Array.prototype.slice.call(arguments));
        document.emits.push(arguments);
        _origEmit.apply(this, Array.prototype.slice.call(arguments));
    }
    var _origOn = main_socket.$emit;
    main_socket.$emit = function(){
        console.log("RECEIVED", Array.prototype.slice.call(arguments));
        document.ons.push(arguments);
        _origOn.apply(this, Array.prototype.slice.call(arguments));
    }
    console.log("Injection complete");
})();

The injection complete runs, so I know the injectjs is working. Then, in my test case where I check to see if it's working at all:

casper.evaluate(function(){
    main_socket.emit('testin');
    console.log("EMITS", JSON.stringify(document.emits));
});

and the output shows basically that there haven't been any emits, even though I just emitted something:

EMITS [{}]

For my end goal I'd like the ability to click a link, assert that the proper socket.io event is emitted, wait 500ms and assert that the server has emitted what I would expect to see back. It seems like this would be an every day use case but I'm having troubles getting the full cycle working.

(note, in my update, I found the error that was happening and it was elsewhere, so I updated to show what isn't working stead of the error)

I found the issue:

In my test_include.js file I was pushing onto the array incorrectly.

document.emits.push(Array.prototype.slice.call(arguments));

Not sure why I was just pushing arguments without slicing it, but that wasn't working.

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