Reusing javascript in java

356 views Asked by At

I've got a challenge in my current organization on re-using the capabilities written on javascript in our java code. Just to give a background:

We have two different automation frameworks:

  1. Java using maven - Uses Cucumber jvm and selenium with page object model - This is mostly maintained by testers
  2. Javascript framework - User cucumber js and selenium web driver - This is maintained by UI developers

The challenge here is we wanted to converge both the frameworks and re-use the capabilities between both. My idea is re-using the page objects at least elements and some helper methods between both the frameworks.

Say for an example:

  1. I have page elements captured in Login.js file and contains few helper methods like generating the random email address.
  2. I should be able to import the Login.js file in my Java class and also should be able to use the page elements and helper method written in javascript.

What I found was cucumber rhino to use the capabilities from java to javascript. Whereas the other way round is not possible.

I can use java 8's scripting engine Nashorn to load the js modules in java, but the same cannot be used if my JS modules are written using Node. And yeah cucumber.js is node module :(

I came across Avatar js which can be used to load the node modules in the jvm. But again the Avatar does not have the support for Cucumber. I tried and failed.

Is there any way to solve this problem?

1

There are 1 answers

2
dasniko On

First of all - forget about Avatar, it's on a very old version and additionally the project is dead!

Using node modules in Nashorn is possible, as long as they are not base on native api. If you need the require() function, you can use jvm-npm. But be sure to resolve all the (transitive) dependencies before on your own or running npm install or similar maven/gradle plugins to resolve npm dependencies.

When loading NPM modules in Nashorn, you should load something like a nashorn-polyfill.js before, because there are some variables, which aren't available in Nashorn, so you have to provide them on your own (maybe, you need some more/additional variables, not yet in my polyfill file available).

I don't know cucumber.js, so I can't provide you tipps how to get cucumber running in Nashorn. But I run React.JS for example in my java server-side code to pre-render the DOM on the server and send it to the client. And React.JS is also a non-trivial NPM lib, but it works like a charm!