A Simple Selenium Script Example Using JavaScript and Safari

In my previous articles I showed how to enable Safari for web automation (hint: developer menu Allow Remote Automation) and how to get your Node.js environment setup on MacOS to begin writing automated web application scripts.    This example is a very basic script to show how to perform a basic web page load (the MySLP site in this case) with some parameter passing that can be expanded in later examples.

Enironment Preparation

My test environment is running on MacOS Safari using Safari 11.   I use phpStorm for WordPress plugin and theme development, so we’ll continue with that here.  phpStorm has excellent JavaScript support and is fairly intelligent on detecting Node.js and Grunt scripts and being able to launch those applets direct from the IDE.

Since this example is short I’ll start with the complete JavaScript app that will launch Safari and open my test site.    It requires Node.js to be installed along with the Selenium Webdriver and Selenium Drivers modules; the setup was covered in a prior article.

The Code

The Explanation

App configuration.   I’ll use this in later example to extend the list of parameters that apply to my specific set of tests so I can try to follow the Don’t Repeat Yourself (DRY) principle as much as possible.

Like the App configuration variable, I also setup a browser configuration variable.   This is passed to seleniumDrivers init() method, so we need to make sure the parameter keys and values fit their accepted values. The current options include:

  • browserName: (‘chrome’ | ‘firefox’ | ‘internet explorer’ | ‘safari’) specify browser name
  • silent: (true | false) set to false for verbose output (default: true)
  • download: (true | false) disable driver download (default: true)
  • deactivate: (true | false) deactivate library (useful when running with custom browser capabilities where driver is provided, eg: for sauceLabs, or browserStack) (default: false)

The my_driver variable is set “higher up the chain” so it is at the top of our application scope.  This allows the app to not pass around a variable holding the Selenium driver object since it will be used nearly everwhere.   This is a Selenium test script after all.

Next is our test case.  Later we will add more test cases to the mix but for a now a simple “load this web page” test is provided.  The sleep is not necessary but I like to have the browser window hang around for a bit so I know something happened.

Last thing we do is get the Selenium “Test Bot” going by calling the Selenium driver’s init() method and following on with the then method of JavaScript, an implementation of promise constructs.    You don’t need to fully understand promise constructs to make your automated scripts but if you’ve not seen the .then() method before that is the root of where it comes from.

Leave a Reply