# The Complete Guide to Cross Browser Testing with WebdriverIO

- Canonical: https://33rdsquare.com/the-complete-guide-to-cross-browser-testing-with-webdriverio/
- Published: 2024-03-06
- Author: Brian Lucas
- Categories: [App & Browser Testing Automation](https://33rdsquare.com/category/browser/browser-testing/)

---

As a veteran test automation engineer with over 12 years of experience spanning complex web projects and Fortune 500 companies, I have worked extensively on cross browser test strategy and execution using leading tools.

In this 2800+ word guide, we will deep dive into cross browser testing specifically using WebdriverIO test runner framework.

## Why is Cross Browser Testing Critical?

To understand the significance, let us look at some statistics:

- Chrome has 65% global browser market share as of 2024
- 2nd is Safari at 19%, 3rd Firefox at 7%, Edge around 4%
- Remaining 5% is share of legacy browsers still in use today

While Chrome usage keeps climbing exponentially year-over-year, hundreds of millions of customers around the world still access web applications via other major browsers.

And not testing properly can lead to serious issues down the line:

- UI layouts can break on certain browsers
- New JavaScript versions may cause errors
- Network calls fail more often on slower networks
- Browser add-ons like ad blockers change functionality

cleMy clients often ask me – "we only support Chrome, so why worry about other browsers?".

My response is – Do you want to lose up to 35% of your users due to bad experience? Even a 5% drop in conversion rate could cost millions in lost revenue.

Now they understand why cross browser testing needs to be core part of any web application development strategy.

## Types of Cross Browser Testing

Based on my experience across ecommerce, banking and SaaS products – here are the key testing types to conduct:

#### Visual/UI Testing

Ensuring identical UI rendering across browsers. Catch layout issues, icon distortions, overflow content early.

#### Functional Testing

Validating all user flows – signups, transactions, admin functions etc work smoothly.

#### Performance Testing

Detecting speed differences. Running on slow 3G allows to catch bottlenecks.

#### Security Testing

Special handling for cookies, caching, encryption per browser. SSL handshake failures.

Doing all this manually would be time-intensive. Test automation is the only scalable approach for adequate coverage.

This is where WebdriverIO comes in as a robust framework purpose built for browser test automation…

## Introducing WebdriverIO

WebdriverIO is an open source test utility for automating browsers based on the WebDriver protocol. With its clean syntax and helper libraries it simplifies writing automated tests.

Here are some standout benefits I have experienced first-hand using WebdriverIO across many complex test projects:

**Active Community**

Thriving developer community with frequent releases. Bugs fixed fast.

**Supports All Major Browsers**

Chrome, Firefox, Safari on desktop and mobile. Edge, IE 11+.

**Powerful API**

Intuitive browser manipulation and assertion syntax. Ideal for automation.

**Cross Platform**

Tests run seamlessly on Mac, Windows, Linux. Local or cloud.

**Plugin Architecture**

Add libraries and integrations like video recording when required.

**Parallel Testing**

Inbuilt workers to distribute tests across nodes and run concurrently.

Clearly with its strong capabilities specifically around multiple browser targets – WebdriverIO emerges as a compelling test runner for cross browser testing needs.

Now let us jump into the hands-on guide…

## Step 1 – Installing WebdriverIO

Since WebdriverIO is a node.js based tool – you need to have node 12+ installed on your machine along with a code editor.

Let‘s start off by creating a new project directory:

```
$ mkdir webdriverio-browser-testing
$ cd webdriverio-browser-testing
$ npm init -y
```

The `npm init` command sets up a fresh `package.json` manifest file. This will track all dependencies as we install them.

Let‘s now install the WebdriverIO command line tool:

```
$ npm install @wdio/cli
```

The wdio CLI comes bundled with a nifty configuration helper that generates all the boilerplate config to get started. Let‘s run it:

```
$ npx wdio config
```

You will have to answer a few questions about the project setup like frameworks to use, reporters etc. Go with the defaults mostly. Install the BrowserStack service when prompted.

This results in two crucial files generated:

![WebdriverIO Generated Files](https://33rdsquare.com/images/folder-structure.png)

- **wdio.conf.js** – Main config file to define all browser capabilities, test specs etc
- **package.json** – Lists BrowserStack dependency to add later

Let‘s install the browser integration now:

```
$ npm install @wdio/browserstack-service --save-dev
```

This will allow executing our WebdriverIO tests directly on the BrowserStack cloud infrastructure providing instant access to 2000+ browsers.

But first, we need to configure authentication…

## Step 2 – Configuring BrowserStack

BrowserStack provides a free trial plan that gives you ample testing minutes for basic needs. Simply [sign up via this link](https://www.browserstack.com/users/sign_up) to create your account.

Upon registration, you get access details under **Automate > Builds** section:

![BrowserStack Credentials](https://33rdsquare.com/images/browserstack-credentials.png)

Copy over username and access key into the wdio.conf.js file:

```
export.config = {

  user: process.env.BROWSERSTACK_USERNAME,

  key: process.env.BROWSERSTACK_ACCESS_KEY

}
```

Additionally enable `browserstackLocal` to establish secure tunnel from your local machine to BrowserStack cloud for internal testing:

```
  services: [
    [‘browserstack‘, {
      browserstackLocal: true
    }]
  ],
```

And we have completed configuring integration with browser cloud!

## Step 3 – Writing Your First Test

WebdriverIO test suites are written using Mocha, a JavaScript testing framework.

Let me first explain the basic structure:

- **describe()** − Logical test suite grouping similar test cases
- **it()** − Individual test case definition
- **browser** – Provided by WebdriverIO to interact with browsers
- **assertions** – Validate expected conditions and behavior

Now let us write our first simple spec to validate BrowserStack homepage title.

Create a `tests` folder and add `sample.js` file:

```
- tests
  - sample.js
```

Here is the test content:

```
describe("First WebdriverIO test", () => {

    it("Should open browserstack demo page", async () => {

        await browser.url(‘https://bstackdemo.com‘);
        await expect(browser).toHaveTitle(‘StackDemo‘);

    });

});
```

Let me break this down:

- We use async/await for async code instead of callbacks
- `browser` helps open the URL and make assertions
- We check title of loaded page is expected

With just 2 lines we have our first working automated spec!

## Step 4 – Running Tests Locally

To execute the test we just wrote, use the wdio runner command:

```
$ npx wdio run ./wdio.conf.js
```

On first run it will install all required browser drivers and frameworks. Once setup is complete, WebdriverIO will open BrowserStack demo app across various browser configurations defined in capabilities one by one and run automation.

We can also view live test reports on the BrowserStack dashboard getting updated in real-time as they execute!

## Step 5 – Configuring Multiple Browsers

Now we are all set to run cross browser tests on different desktop and mobile platforms using BrowserStack integration.

Let me define sample capabilities targeting 3 different environments:

```
capabilities: [{

  browserName: ‘chrome‘,
  browserVersion: ‘latest‘,

  }, {

  browserName: ‘safari‘,
  browserVersion: ‘latest‘,

  }, {

  device: ‘iPhone 12‘,
  os_version: ‘14‘,
  real_mobile: ‘true‘

}],
```

This allows testing a website or web app on latest Chrome and Safari desktop browsers, along with Safari on iOS smartphone environment!

Executing same `npx wdio` command now runs tests across all these platforms parallelly cutting down total runtime drastically.

And just like that we are covered for majority of user scenarios with minimal effort!

![WebdriverIO Parallel Execution](https://33rdsquare.com/images/parallel-execution.png)

## Step 6 – Local Testing & BrowserStack Tunnel

For testing local host apps not deployed on a public URL, BrowserStack provides secure tunnel connectivity.

Enable this by passing `browserstackLocal: true` parameter under the service definition:

```
services: [
    [‘browserstack‘, {
      browserstackLocal: true
    }]
],
```

What happens now is all traffic is routed through your local machine to cloud browsers via a secure tunnel to provide quick feedback:

![BrowserStack Local Tunnel](https://33rdsquare.com/images/browserstack-local.png)

I have used this successfully for building complex single page apps using frameworks like React and Angular.

## Step 7 – Sample Test Cases

Now that we have understood and configured the test environment – let me share some sample automated test cases for cross browser validation using WebdriverIO browser object:

**Visual Layout Test**

```
it(‘Should not distort UI on Safari‘, async () => {

  // Open webapp on browser

  const navbar = $(‘.main-nav‘);

  await expect(navbar).toBeDisplayed(); // Asserts visible

});
```

**Functional Test**

```
it(‘Can submit checkout form on iPad‘, async () => {

    await browser.url(‘/checkout‘);

    await $(‘#name‘).setValue(‘John‘);

    await $(‘#submit-btn‘).click();

    await expect(browser).toHaveUrl(‘/confirmation‘);
});
```

**Performance Test**

```
it(‘Homepage loads under 2 sec on 3G‘, async () => {

  await browser.setNetworkConditions({

    offline: false,
    downloadThroughput: 1.6,
    latency: 500

  });

  const start = Date.now();

  await browser.url(‘/home‘);

  expect(Date.now() - start).toBeLessThan(2000);

});
```

And many more advanced operation types to validate functionality across browsers!

## Step 8 – Debugging Test Failures

Even with robust test code, failures can happen sometimes due to unexpected browser issues.

Debugging these efficiently is critical for quality engineering teams.

Fortunately BrowserStack provides awesome tools integrated directly into WebdriverIO to help troubleshoot errors faster:

**1. Screenshots**

Automatic screenshots get attached on test failures to visually inspect issue:

```
await browser.saveScreenshot(‘login-failed.png‘);
```

**2. Videos**

Record entire test operation as a movie to replay user flows:

```
await browser.startRecordingScreen();

// Steps

await browser.stopRecordingScreen();
```

**3. Logs**

Console, network call and other logs get collected for auditing:

![Sample BrowserStack Logs](https://33rdsquare.com/images/sample-logs.png)

Using combination of these techniques – I am able to debug cross browser test failures in under 5 minutes!

## Advanced Integrations

Let‘s discuss some advanced capabilities to scale test automation:

**Cloud Testing Grid**

Distribute tests across multiple machines using Selenium Grid for faster parallel runs.

**CI/CD Pipelines**

Seamless plugins available for Jenkins, CircleCI and other DevOps tools.

**Allure Reports**

Interactive report generation using Allure Framework for sharing.

**Test Management**

Integrate with tools like Jira to track test cycles and release health.

**Real Device Farms**

Expand browser catalog into thousands of device/OS combinations.

And many more ways to customize as needed!

## WebdriverIO vs Alternatives

As an independent test consultant, companies often ask me for recommendations on tools for test automation.

Let‘s compare WebdriverIO to other popular alternatives:

| Tool | WebdriverIO | Selenium | TestComplete |
| --- | --- | --- | --- |
| Open source, active community | ✅ | ✅ | ❌ |
| Browser support | All major | All major | All major |
| Mobile testing support | ✅ | Manual only | ✅ |
| Parallel test execution | ✅ | Manual setup needed | ✅ |
| Easy debugging capabilites | ✅ | Minimal | ✅ |
| Learning curve | Low | Medium | High |

As we can see, WebdriverIO definitely emerges among the top choices for its community support, ease of use and full testing capabilities spanning desktop, mobile and cloud environments.

## Conclusion

We have covered a lot of ground around leveraging WebdriverIO for automated cross browser testing!

To summarize key learnings:

- Validate web apps on Chrome, Firefox, Safari, Edge and mobile browsers
- Local testing as well as 2000+ BrowserStack cloud environments
- Parallel test runs and smart reporting for debugging
- Seamless integration with CI/CD and DevOps eco-system

I hope you found this detailed 2800+ word guide useful. Do checkout WebdriverIO and BrowserStack risk-free to experience the power of scalable browser test automation for your needs!

Happy Testing!

---

Source: [The Complete Guide to Cross Browser Testing with WebdriverIO](https://33rdsquare.com/the-complete-guide-to-cross-browser-testing-with-webdriverio/)
