Executing Raw Javascript in Protractor

This post is part of a ten-part series on how to write better Protractor tests. You can find the rest of the series here.

Last time we talked about how you can inject Angular modules for HTTP mocking. But what if you simply want to execute arbitrary javascript?

Executing sync javascript in Protractor is pretty straightforward:

or

You can also pass a regular function to Protractor:

Notice here that our function has a return value. browser.executeScript returns a promise, which we can call .then on. The return value of the executed function is the first argument to the callback function (phew).

Note that you’ll run into problems if you try to return anything other than javascript primitives.

Pretty easy. But what if you need to execute an async script and get the result? We cover that in the next post

Learn Protractor in a few hours with our online course

Protractor is a one of the best ways to ensure your app is working correctly because you can write code that acts like a real user. But Protractor can also be confusing and difficult to work with when you're just starting out. We've put together an online course that will help you become a master at Protractor.

You'll save tons of time and frustration learning Protractor because we've worked out everything you need to know. Become a Protractor testing master today!