Today I will write about javascript expressions executing in browser consoles during testsing. Sometimes you need to inject some javascript code into the web page, for additional testing, additional features or by client request.
In some cases a simple console.log() could do the trick, but sometimes it is not enough , especially when you use an already opened cmd.exe through which you run tests, because that way the console.log() will write in that console not into the browser’s.

The other option is the eval() function, that turns strings into expressions and/or functions. However the use of eval() is ill advised as it is slow and dangerous, especially on behavior of the website. It requires extra caution and reckless use could do more harm than good. The desired expressions need to be put into extra html tags, to be shown properly as desired and it slows down the loading of web page.
However there are some neat solutions in webdriver cliens for testing such requests. This example will be written in a node.js client for webdriver/selenium 2 (https://github.com/admc/wd).

This node.js client offers execute() and safeExecute() to manage code injection into browser. The execute() inject a snippet of JavaScript into the page for execution in the context of the currently selected frame, while safeExecute() safely execute script within an eval block, properly wrapped so you don’t need to think about it extra. Feel free to experiment which is more convenient for your testing or work. For asynchronous JavaScript code injection use executeAsync() and safeExecuteAsync().

Example:

var
yiewd = require('yiewd'), 
asserters = require('wd/lib/asserters.js');

it('TestCase: JavaScript snippet injection into currently selected frame', function(done) {
	driver.run(function*() {
		try{
			//simple execute injection
			yield this.execute("Your JavaScript code line");

			//or safeExecute with eval
			yield this.safeExecute("Another code line");

			/*
			 * Add additional executions commands as many you require...
			 */

			//refresh the page to see the changes
			yield this.refresh();
			
			//wait for some desired element to appear  waitForElementByXPath/ waitForElementByCss
			yield this.waitForElementByXPath("You desired xpath to wait",asserters.isDisplayed,10000);

			//if all went well exit
			done();
		} catch(e) {
			//if something went wrong exit with error
			done(e);
		}
	});
});

Also take note, that execute your script function by function, code line by line where possible, so the execution goes smoothly as possible, do not push all code into single execution command, it might not give back the desired behavior.

For additional questions please feel free to post a comment and I will reply on it when available.

Posted By Arnold Gergelj

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>