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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

I think button() would have to return a value for that to work, no?
You are right.. If so, is it possible to fix this issue?
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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.