0

I want to test a front end vanilla javascript using Selenium in java. I can easily open the page click on some stuff etc, but I couldn't figure out exactly what is the best practices to assert tests. Mainly, can we get the variables after clicking on some buttons, for example let's say:

function button(){
  variable = 2;
}

Let's say some button calls the function above, in selenium I can click on the function but is there a way to call the variable and do something like;

AssertEquals(2, driver.getVariableFromJavascriptAfterClick())

If not, how should I test something like that.

Thanks

golgetahir
  • 98
  • 1
  • 7

1 Answers1

0

Looks like all you need to do is

JavascriptExecutor js = (JavascriptExecutor) driver;
int val = js.executeScript("return button();");
AssertEquals(2, val);

For more details see this reference

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • I think button() would have to return a value for that to work, no? – pcalkins Oct 26 '21 at 20:08
  • You are right.. If so, is it possible to fix this issue? – Prophet Oct 26 '21 at 20:09
  • well, the example javascript function there is not really usable... I think the OP needs to provide a specific example of what they're trying to do. Personally I'd focus on the DOM for Selenium tests. To test the javascript portion of the page I think a "debug" version of the site should be created. You could expose some things to the DOM/Selenium for convenience. – pcalkins Oct 26 '21 at 20:31
  • Hey guys, thank you for attention and answers. I am trying to build an autonomous testing for a web page @pcalkins .The real question is what is the best practices for opening the webpage ( either with mock objects or real ) and running it to see the output of some methods and making assertions. For example if I open the page with selenium and click on some stuff, can I get the related functions outputs at that run, no right? Executor seems it will run only that method, and global variables etc. links will be missing. Maybe I am thinking like testing a java code, can you guide me here. – golgetahir Oct 29 '21 at 15:35
  • I don't know much about "best practices"... but I'd use Selenium to test the front-end. So make sure that whatever that javascript does is reflected in the DOM. For testing Javascript I would go another route. Maybe build asserts into the scripts. For convenience, you might expose some of the javascript return objects to the DOM so Selenium can check them. – pcalkins Oct 29 '21 at 17:41