WebDriverIO and CrossBrowserTesting

Applies to CrossBrowserTesting SaaS, last modified on January 10, 2023

WebDriverIO is a powerful and easy to use command-line tool for running Selenium-JS tests that provides language bindings for the powerful browser-driving tool Selenium. Its test runner allows you to write your tests in a synchronous way so you are not constantly in the world of asynchronous coding. WebDriverIO integrates easily with the CrossBrowserTesting platform, so you can perform tests on a wide variety of OS/Device/Browser combinations, all from one test.

Tip: For this document, we provide an example test located in our WebdriverIO GitHub Repository.

Start from scratch

You can configure WebDriverIO to use many different testing frameworks, such as Chai or Mocha. For more information, see WebDriver Options. We will start by writing a simple test using WebDriverIO with Mocha.

Create a simple test

  1. Create a folder for your test.

  2. From inside that folder, run the following commands:

    Note: The npm init command will prompt for information about your project. If you are unsure, it is fine to leave those fields blank.

    npm init -y
    npm install --save-dev @wdio/cli
    npm install --save-dev @wdio/local-runner
    npm install --save-dev @wdio/spec-reporter
    npm install --save-dev request

npm init -y starts your project, npm install --save-dev @wdio/cli installs WebDriverIO into your project, npm install --save-dev @wdio/local-runner allows running tests locally, npm install --save-dev @wdio/spec-reporter formats the test output in the spec style, and npm install --save-dev request installs the request module.

Test with Mocha

The process of using WebDriverIO with other frameworks will vary slightly with each framework. Several frameworks are supported with the configuration tool, which can be started up with the ./node_modules/.bin/wdio config command. This will give a series of prompts and create a configuration file with the information you provide. We will manually create our configuration file for this example.

  1. Install the WebDriverIO/Mocha adapter and the CrossBrowserTesting WDIO service:

    npm install --save-dev @wdio/mocha-framework
    npm install --save-dev @wdio/crossbrowsertesting-service

  2. Make a configuration file.

    Note: In this guide, we will make one manually, but if you would like to use WebDriverIO's configuration tool, you can run it with ./node_modules/.bin/wdio config.

    Save the following code as wdio.conf.js in the root directory of your project:

    exports.config = {
        runner: 'local',
       
        hostname: 'hub.crossbrowsertesting.com',
        port: 80,
        path: '/wd/hub',
       
        services: ['crossbrowsertesting'],
        user: process.env.CBT_USERNAME,
        key: process.env.CBT_AUTHKEY,
        cbtTunnel: false, //set to true if a local connection is needed
        
        specs: [
            './test/specs/**/*.js'
        ],
        exclude: [
            // 'path/to/excluded/files'
        ],
     
        maxInstances: 10,
        
        capabilities: [{
            maxInstances: 5,
            name: 'WDIO Selenium Test Example',
            platform: 'Windows',
            browserName: 'firefox',
            record_video: 'true'
        }],
      
        logLevel: 'info',
        
        bail: 0,
        
        baseUrl: 'http://localhost',
        
        waitforTimeout: 10000,

        connectionRetryTimeout: 90000,
        
        connectionRetryCount: 3,

        framework: 'mocha',

        reporters: ['spec'],
        
      
        mochaOpts: {
            ui: 'bdd',
            timeout: 60000
        }
    }

  3. Place your tests in the /test/specs directory we specified in the config file.

    Here is the sample test we will use saved in a file named login.js:

    const request = require('request');
    const assert = require('assert')

    describe("Login form", function(){
        this.timeout(5 * 1000 * 60);
        
        it('should have the right title', () => {
            browser.url("http://crossbrowsertesting.github.io/login-form.html");

            //Enter the username
            let username = browser.$("#username");
            username.click()
            username.setValue("username");

            //Enter the password
            let password = browser.$("#password");
            password.click()
            password.setValue("password");

            // Click "Login"
            browser.$("div.form-actions>button").click();

            let title = browser.getTitle();
            try {
                //Check title
                assert.deepEqual(title, "Login Form - CrossBrowserTesting.com");
            } catch(e) {
                //Set score and throw exception so WebDriverIO detects it
                setScore("fail");
                throw(e);
            }
            setScore("pass");     
        });
    });

    //Helper to set the score
    function setScore(score) {

        var result = { error: false, message: null }

        if (browser.sessionId){
            
            request({
                method: 'PUT',
                uri: 'https://crossbrowsertesting.com/api/v3/selenium/' + browser.sessionId,
                body: {'action': 'set_score', 'score': score },
                json: true
            },
            function(error, response, body) {
                if (error) {
                    result.error = true;
                    result.message = error;
                }
                else if (response.statusCode !== 200){
                    result.error = true;
                    result.message = body;
                }
                else{
                    result.error = false;
                    result.message = 'success';
                }

            })
            .auth(process.env.CBT_USERNAME, process.env.CBT_AUTHKEY);
        }
        else{
            result.error = true;
            result.message = 'Session Id was not defined';
        }
    }

Convert existing test suites

If you are already a WebDriverIO user, you can quickly change your current tests by editing your wdio.conf.js file:

Before:

var options = {
    desiredCapabilities: {
        browserName: 'firefox'
    }
};

Now:

exports.config = {
  runner: 'local',
  hostname: "hub.crossbrowsertesting.com",
  port: 80,
  path: '/wd/hub',
  user: '[email protected]',        // the email address associated with your CBT account
  key: 'yourauthkey',               // find this under the "Manage Account page of our app"
  
  capabilities: {
    name: 'Selenium Test Example',
    build: '1.0',
    platform: "Win10", // Gets the latest version by default
    browserName: 'firefox', // To specify a version, add a version: "desired version"
    record_video: 'true',
    record_network: 'false'
  }
  
}

Run your test using the following command:

./node_modules/.bin/wdio

As you can see, we are now pointing the test to our hub rather than a local driver instance.

Use Local Connection

If you would like to test behind your firewall or access non-public sites, you can use our Local Connection tool through our WebdriverIO service.

  1. Install the CrossBrowserTesting WebdriverIO service:

    npm install --save-dev @wdio/crossbrowsertesting-service

  2. Add the following to your wdio.conf.js file:

    exports.config = {
      // ...
      services: ['crossbrowsertesting'],
      cbtTunnel: true,
      // ...
    }

As you can probably see from our test, we visit Google, and output the title we see. If the title is correct, then we will set the score to pass.

See Also

Test Frameworks and Tools
About Selenium Testing
Selenium and JavaScript
CucumberJS
InternJS
Jasmine
Jest
Karma
Mocha
NightwatchJS
Protractor

Highlight search results