Question

I have the following:

casper.then(function addToBag(){
    this.evaluate(function (){
        //register sub method - then emit custom event
        mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
            casper.emit('addToCart.loaded');
        });
        //trigger add to cart click
        $('.product-selection input[type=submit]').click();
    });
});

The click trigger activates the emit, inside the event function:

casper.on("addToCart.loaded", function checkAddToCartResponse(){
    console.log("Added");
    test.assert(true,'Add to cart successful');
}),

However, it doesn't seem to run - is this the correct way of running a test when an event has finished?

Was it helpful?

Solution

The event is not emitted because there is no casper instance inside the page context (inside the evaluate context).

You would need to set some flag that the event was emitted.

casper.then(function addToBag(){    
    this.evaluate(function (){
        //register sub method - then emit custom event
        window.casperEventEmitted = null;
        mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
            window.casperEventEmitted = 'addToCart.loaded';
        });
        //trigger add to cart click
        $('.product-selection input[type=submit]').click();
    });
});
// wait here

and then wait for the event to be set

var timeout = 10000; // msec, some sensible timeout for your event
casper.waitFor(function check() {
    return this.getGlobal('casperEventEmitted') == 'addToCart.loaded';
}, function then() {
    return this.evaluate(function() {
        window.casperEventEmitted = null; // reset for next time
    });
    this.test.pass("Event triggered");
}, function onTimeout(){
    this.test.fail("Event triggered");
}, timeout);

Of course it would be nicer to manage the events in a queue and not as a single string.

The good thing is that there is no break out from the control flow as it would happen with a custom event like in the case of the other answer.

OTHER TIPS

Use inside the evaluate callback:

console.log("casper-event:add:[1234]");

then can do it like this (not tested):

casper.on('remote.message', function(msg) {
   if(msg.indexOf("casper-event:" == 0))
   {
       var event = msg.replace(/^casper-event:/, '').replace(/:.*$/, '');
       var result = JSON.parse(msg.replace(/^casper-event:.*?:/, ''));
       this.emit(event, result);
   }
});

casper.on('add'........
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top