Develop Selenium webdriver scripts using javascript

advertisements

Can we develop selenium webdriver scripts using javascript only. If yes what are the advantages of using javascript instead of using java or C# or any language.? In what scenario we should consider Javascript over other languages?

Thank you.


There are numerous Javascript frameworks written on top of the JS selenium bindings (webdriver.io, nightwatch, protractor).

Benefits of JS over C# or Java

  • Less boilerplate
  • Grunt or gulp for build automaton > maven, msbuild or even gradle
  • Better integration with front-end frameworks (protractor)
  • JS is generally used in all web projects so it works as a universal language that all devs can understand.
  • NPM for dependency management and the massive number of libraries in it that may drastically reduce your workload.

Drawbacks

  • The Java bindings have more documentation / resources available to debug issues.
  • Speed (I find using the AjaxPageFactory in Java to be a lot faster than protractor and I have not found an equivalent in Javascript)
  • Promises can be complicated coming from Java or C#.
  • No support for Microsoft Edge currently.

As far as specific use cases if you use Angular heavily on the front-end Protractor is a tool designed specifically for functional testing of angular and should be used over C# or Java. Protractor can be used with frameworks such as React.js but it wasn't designed for it and you may need to include a lot of waitForElement type code.

A few things I have found really nice about protractor specifically is the configuration for more comprehensive multi-browser testing. To set this up in Java or C# involves a lot of configuration and in Protractor it could be as simple as make two changes to your conf.js file. I also find myself using a lot of grunt plugins to set up and tear down my tests which are very simple to configure.

I would recommend using Babel.js so you can utilize the es2015 JS syntax which makes the transition from Java or C# simpler due to the inclusion of classes and I personally find it much more cleaner for writing page objects.

One thing to be aware of is a lot of simple actions in Selenium for Java and C# are more complicated in Javascript because most actions return promises.

Java Version

int previousNumberOfItems = driver.findElements(By.className(".item")).size();
driver.findElements(By.cssSelector(".addItemButton")).click();
int currentNumberOfItems = driver.findElements(By.className(".item")).size();
assert.AssertTrue(currentNumberOfItems .contentEquals(previousNumberOfItems +1));

Protractor (JS) Version

element.all(by.className(".item")).count().then(function(number){
    element(by.css(".addItemButton")).click();
    expect(element.all(by.className(".item")).count()).toBe(number+1);
});

I can't really speak for nightwatch or webdriver.io they may be much better for testing non-angular apps using Javascript.