{{announcement.body}}
{{announcement.title}}

Automated Cross-Browser Testing With Protractor and Selenium

DZone 's Guide to

Automated Cross-Browser Testing With Protractor and Selenium

A look into how to use these two popular testing frameworks to test web applications, with special attention paid to Angular-based apps.

· Web Dev Zone ·
Free Resource

What Do We Mean By JavaScript Test Automation Frameworks?

There has been a major growth in JavaScript framework usage over the past few years, the reason is, nowadays most of the apps are developed using technology like Angular or React. In fact, initially, Angular was the first choice for web developers, however, by the end of 2018, we could see major dominance over the web for React. React may even continue to dominate 2019 as well.

JavaScript test automation frameworks are end-to-end frameworks specialized to run automation scripts for web applications. However, choosing the right one can be very challenging based on the following criteria:

  • End-to-End Testing
  • Assertion library
  • BDD/TDD Integration
  • Integration test
  • Regular updates from the community
  • Cross Browser Layout Testing
  • Visual Regression Testing

Why JavaScript Frameworks Are Necessary

JavaScript is not news to web developers. Most of the developers in an organization write JavaScript code for developing web applications, unit tests, etc. Here are some reasons for considering JavaScript framework pivotal:

  • Easy to follow shift left testing for better product quality.
  • Provides developers the flexibility of generating end-to-end tests, along with unit testing for faster and reliable shipping.
  • More collaboration between Dev and QA in the same language for test automation.
  • Helps to implement Dev/QA tests and pair programming on the test automation side.
  • You team can be more flexible and productive when working in the same language.

What Is Protractor?

Protractor is a JavaScript framework for end-to-end test automation of Angular-based applications. It tests against your application in a real browser, as a real user would.

Protractor is built on top of WebDriverJS (Selenium) and apart from tje default locator, it comes with Angular-specific locator strategies. It’s not intended to test only Angular applications, and can help write automation tests for applications based in other frameworks.

What Makes Protractor a Good Fit for Your Automation Test Scripts?

Protractor is an open source, end-to-end test automation framework by Google, which makes it a reliable, renowned, and up-to-date framework. Protractor is a Node.js package that supports testing frameworks like Jasmine, Moch, and Cucumber.

Key Features of Protractor

  • Protractor is developed as a wrapper and built around Selenium WebDriverJS and Selenium Server. All key features of Selenium WebDriverJS and additional implementation helps to provide better automation supports and less maintenance when compared with Selenium.
  • Protractor offers new locator strategies on top of a native locator which actually helps to locate elements in the DOM easily.
    • by.model, by.binding, by.repeater, etc.,
  • Protractor supports the page object design pattern, meaning it helps you write clean and readable code.
  • Protractor makes use of Selenium Grid to initialize, control, and run browser instances.
  • It can easily integrate with Jasmine, Mocha, and Cucumber to write tests.

Advantages of Protractor When Combined With Selenium:

  • Excellent speed compared to other tools or libraries.
  • Supports cross-browser parallel testing through multiple browsers.
  • No need to work on synchronization strategy. Protractor has built-in capabilities and intelligence to connect with Angular and knows when Angular has finished rendering the DOM.
  • Angular-specific locator support.

Getting Started With Cross Browser Automation Testing With Protractor and Selenium

Here are the prerequisites required for performingcross-browserr automation testing with Protractor and Selenium on Windows:

  • Node.js
  • Install Protractor using npm
  • Update the WebDriver manager and start up a server
  • Visual Studio Code

Setting Up an Automation Environment for Testing With Protractor and Selenium in Windows

This section has detailed steps explaining how to setup an environment for performing end-to-end cross browser automation testing with Protractor and Selenium through Windows.

Step 1: Installation of Node.js

You need to install npm for Node.js.

What Is npm?

npm is a free package manager for JavaScript development which helps you to download all public software packages.

What Is a Package Manager?

A package in Node.js contains a group of files that you need for a module. A module is a collection of JavaScript libraries that can be included in your project.

To install Node.js, click here.
Node.js Installation

Once you are done downloading the installer, run it as administrator.

Click on the ‘Next’ button in the Node.js setup window to proceed further.

Node.js Installation

Click on the checkbox to accept the license agreement and click on the Next button.

Node.js Installation

Keep the default Windows location or feel free to change the location and click Next.

Node.js Installation

Thereafter, click on Next and the Install button. Wait for a couple minutes for the installation to complete.

You will see the following screen after the installation is done.

Node.js Installation

To verify npm gets installed on your machine, use the following command: npm –version.

Node.js InstallationStep 2: Install Protractor Using npm

To download a package, open a command prompt and supply the following command:

npm install –g protractor

The below snapshot indicates that protractor is installed successfully.

Protractor Installation

To verify the installed Protractor version, supply the following command:

protractor –version


Protractor InstallationStep 3: Update WebDriver Manager and Start Up a Server

To update the WebDriver manager, supply the following command:

webdriver-manager update

Once you give the above command, it will download all the necessary dependencies.

Protractor Installation

The WebDriver manager is a helper tool to download necessary binaries. It will help to start and stop Selenium Server.

To start up the Selenium Server use:

webdriver-manager start
Selenium Server

To verify Selenium Server is running in the browser, use the following URL: http://localhost:4444/wd/hub.

Protractor test will send request to this server and control a local browser where you can see information about the status of the server. So, you could later go ahead and run your JS automation script with Protractor and Selenium.

Step 4: Installation of Visual Studio Code

What Is Visual Studio Code?

Developed by Microsoft, Visual Studio Code is a source code editor for Windows, Mac, and Linux operating systems. It is similar to other editors like Eclipse or IntelliJ. It supports a number of programming languages.

Double click on the Visual Studio installer and click the “Next” button.

VS Code

Click on “I accept the agreement” in the Setup – Visual Studio Code window.

VS Code

Keep the default installation location or feel free to change the path in your computer and click the “Next” button.

VS Code

To continue, click “Next” and check Desktop Shortcut if you want, then finish the installation.

Once the installation is complete, the following window will appear.

VS Code

Click the “Finish” button and your Visual Studio Code editor will open up.

VS Code

Click on the language which you want to install, I would suggest you install JavaScript and TypeScript for for executing automation test cases using Protractor and Selenium. Once clicked, it prompts you to select the “ok” button. It will take few seconds to install the selected languages.

Writing Sample Code for Automation Testing With Protractor and Selenium

Now, we will have a look at a sample JavaScript code for automation testing with Protractor and Selenium, and execute the test in a local instance.

To run a Protractor test for end-to-end automation, you need two files:

  • Specs
  • Config

Specs: Specs are actual test suites that have more than one test case and were designed in Javascript using the Jasmine framework.

What Is Jasmine?

Jasmine is a BDD (Behaviour Driven Development) testing framework for JavaScript. This framework helps you to write clean and readable code. To know more about Jasmine, visit their official docs, here.

Executing a Local Instance for Automation Testing With Protractor and Selenium WebDriver

Here is the simple example config file and how to write basic code in Protractor using Jasmine.

Config.js:

exports.config = {   
seleniumAddress: 'http://localhost:4444/wd/hub',   
specs: ['lambdatest_spec.js'],   
multiCapabilities: 
[{     'browserName': 'chrome',   },   
{     'browserName': 'firefox'   }] 
}

The above snapshot shows the syntax of and how to define:

  • seleniumAddress: Protractor makes use of Selenium Grid to run your test in a specified browser.
  • specs: specs indicate the test suite that you can mention in one or more spec files to run multiple tests.
  • Capabilities: This is the place where you can capability setting for your test configuration for example the browser version, platform, etc. If no capabilities are provided then it uses the Chrome browser on your machine by default.
describe('To verify Angular and non Angular application test', () => {     
it('To verify page title of Lambdattest', 
() => {         browser.get("https://lambdatest.com");         
element(by.css('p.home-btn > a.home-cta')).click();         
expect(browser.getTitle()).toEqual('Signup - LambdaTest App | Free Cross Browser Testing Tool');     
}); 
});

We will see a clear explanation of what the above code indicating.

  • describe – describe is the keyword from Jasmine to write the syntax for test suites. This is the definition of a collection of test cases in your script file.

  • it  – This is the keyword for test cases to meet a specific condition. There can be more than one it  added under describe in the Jasmine framework.

In the above code, we launch the browser, navigate to sign up page, see that the title gets matched, and pass the results.

To run your test:

In Visual Studio Code: Go to View Menu-> Click “Terminal” and use the following command:

image-lambdatest
Syntax to Run Your Test Suites With Protractor Followed by the Config File Name

Note: Before you run your test, make sure to run the Selenium Grid via the following commands:

  • webdriver-manager start

Selenium Grid

After executing the above test, we get the following failures (which are expected):

Selenium Grid

The above screenshot indicates the website https://lambdatest.com was not developed using Angular components. This is the best real-time example to realize how Protractor works while launching the browser. As we mentioned in the “Advantages” section above, Protractor tries to connect with Angular while launching the application. The moment Protractor identified and realized it’s not an Angular component, it recommended us to turn off waiting for Angular.

To address this problem, we have a method called browser.waitForAngularEnabled(false);.

Now, the method is added in the script and, as you can see in the below screenshot, Protractor now supports non-Angular applications.

describe('To verify Angular and non Angular application test', () => {
    it('To verify page title of Lambdattest', () => {
        browser.waitForAngularEnabled(false);
        browser.get("https://lambdatest.com");
        element(by.css('p.home-btn > a.home-cta')).click();
        expect(browser.getTitle()).toEqual('Signup - LambdaTest App | Free Cross Browser Testing Tool');
    });
});

After executing the test, the test is passed successfully.

Protractor

Executing Parallel Execution For Automation Testing With Protractor and Selenium WebDriver (Local)

In this example, I’m trying to use the same script we used above, except with a small tweak in the conf.js page. So I copied the existing config file and updated the configuration details to run the same test in multiple browsers to perform cross-browser parallel testing.

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['lambdatest_spec.js'],
  multiCapabilities: [{
    'browserName': 'chrome',
  },
  {
    'browserName': 'firefox'
  }]
}

In the above examples, I modified multiCapabilities and included the Firefox browser. This is great, because no maintenance is needed when peforming automation testing with Protractor and Selenium. Protractor has built-in code to run cross browser automation.

Protractor

This time we run both tests in Chrome and Firefox, which execute and pass the results.

So far we have seen how to run tests in Protractor for non-Angular applications. The below section will show how to run tests on Angular-based applications in parallel and in the cloud.

Executing Parallel Execution for Angular Applications

To run parallel execution for Angular applications, the configuration remains the same but I implement it using async-await to queue up events.

Make sure to disable the promise manager in your config file.

exports.config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['calculator_spec.js'],
  multiCapabilities: [{
    'browserName': 'chrome',
  },
  {
    'browserName': 'firefox'
  }],
  SELENIUM_PROMISE_MANAGER: false
}
describe('To verify super calculator functionality', () => {
    it('perform addition with 2 values', async () => {
        await browser.get('http://juliemr.github.io/protractor-demo/');
        await browser.element(by.model('first')).sendKeys('25');
        await browser.element(by.model('second')).sendKeys('25');
        await browser.element(by.id('gobutton')).click();
        expect(await browser.element(by.css('h2.ng-binding:nth-child(5)')).getText()).toEqual('50')
    })
})

Conclusion

By delivering Protractor as an extensive, end-to-end testing framework, Google has put a lot of effort into making QA engineer's work easier. There are a lot of npm modules available to work with REST APIs, data generators, etc., along with browser automation to integrate all types of automation. All these point toward Protractor being the right choice for automated cross-browser testing of Angular as well as non-Angular applications.


If you enjoyed this article and want to learn more about Automated Testing, check out this collection of tutorials and articles on all things Automated Testing.

Topics:
automated browser testing ,automation testing ,web dev ,angular tutorial ,browser testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}