Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use protractor with Java

I want to use Protractor on Java and not on Node.js. Is it possible to use Protractor with Java or Python? We do not want to add another technology for testing and want to use existing technologies.

like image 804
user3762901 Avatar asked May 01 '15 07:05

user3762901


People also ask

Can Protractor be used with Java?

Protractor is a JS library so you can't run it in Java and testing Angular apps without Protractor is difficult because your tests code needs to wait for Angular processes to complete before interactions like clicking occur.

Can I use Protractor without angular?

Protractor can be used for non angular applications.

Is Protractor better than selenium?

Is protractor better than selenium? Both Selenium and protractor are automated test tools for web applications. Both are used to automate Angular Applications. As Protractor is specially designed for angular applications, so if you are testing angular applications, it is better to opt for a protractor.


1 Answers

Protractor is a JS library so you can't run it in Java and testing Angular apps without Protractor is difficult because your tests code needs to wait for Angular processes to complete before interactions like clicking occur.

Fortunately, Angular has made it easy to identify when it's done processing.

There is a JS function that takes a callback and will notify you once the Angular is ready.

angular.getTestability("body").whenStable(callback);

NOTE: That this works with Angular 1.4.8. Some other versions of Angular have a different method that is similar.

You can invoke the testability method from your Java test code using the following simple method or something similar.

private void waitForAngular() {

    final String script = "var callback = arguments[arguments.length - 1];\n" +
            "var rootSelector = \'body\';\n" +
            "var el = document.querySelector(rootSelector);\n" +
            "\n" +
            "try {\n" +
            "    if (angular) {\n" +
            "        window.angular.getTestability(el).whenStable(callback);\n" +
            "    }\n" +
            "    else {\n" +
            "        callback();\n" +
            "    }\n" +
            "} catch (err) {\n" +
            "    callback(err.message);\n" +
            "}";

    ((JavascriptExecutor) driver).executeAsyncScript(script, new Object[0]);
}

Call waitForAngular() before interacting with the driver with a method like click.

You may want a different rootSelector from 'body' and you may want to throw an error if angular doesn't exist but this works well for my needs.

Protractor provides other selectors which may make testing an Angular app easier but personally I use ID and Class selectors so I don't need them.

like image 82
Scott Boring Avatar answered Nov 09 '22 22:11

Scott Boring