Search code examples
javascriptnode.jsselenium-rcsoda

How does soda.js chaining API work for selenium testing sites using node.js


I'm attempting to create a node.js script using soda.js for organizing and writing Selenium scripts. The problem I am running into is that I fundamentally do not understand the soda.js chaining philosophy, especially the and() method and the docs are very weak in explaining how it works.

Imagine the following test case:

var soda = require('soda');
var assert = require('assert');

var browser = soda.createClient({
    host: 'localhost',
    port: 4444,
    url: 'http://www.google.com',
    browser: 'firefox'
});

browser
    .chain
    .session()
    .open("http://www.google.com", function() {
        console.log("open complete");
    })
    .and(function() {
        console.log("and");
    })
    .and(function() {
        return function(browser) {
            console.log("and2");
        }
    }())
    .end(function() {
        console.log("end");
    })

My understanding of the chaining API was that it was to prevent callback hell. So if I call browser.method1().method2().method3(). Then method2 would wait for method one. method3 would wait for method2() etc. Giving you the ease of synchronous, but the functionality of evented.

I expect

open complete
and
and2
end

I get

and
and2
open complete
end

What? It clearly has something to do with the and method, which I thought was declaring your own arbitrary functions, but it doesn't seem to be following the queue order. As you can see in the test case I've tried two methods of declaring the and function, one using a self-executing function closure, and the other with a standard anonymous function. Same result in both cases. How do I get the and() to follow the queue order?


Solution

  • After much banging my head I was finally able to figure out the way this works only by pouring over the source code for soda on github. Basically the .and() method fires immediately. Each chained request just adds to a queue and it does not begin processing the queue until it hits an .end() call.

    In this way, code inside an and() will always process before the callback from any other call. In this way and() is primarily used for queuing up dynamically defined actions, and it is not useful for responding to previously fired actions, those should be done in callbacks instead.