Web

Setup New Project

Introduction

Welcome to the WebDriverIO Setup Documentation! In this comprehensive guide, we will walk you through the essential steps and best practices for setting up WebDriverIO, a powerful and flexible JavaScript automation framework, to supercharge your web testing efforts.

Requirements

  • Node.js should be installed on your computer.
  • Knowledge of JavaScript.
  • Package Manager: npm or yarn (npm comes bundled with Node.js)
  • Code Editor: A code editor like VSCode or PHPStorm.
  • WebDriver-Compatible Browser: Common choices are Google Chrome and Mozilla Firefox.

Setup WebDriverIO Project

  1. Open Code Editor.
  2. Create a folder with project name.
  3. Open the terminal of that folder. Look for the terminal option on the Code Editor.
  4. The path in the terminal window should contain the project folder name. Refer to the image below:
  5. Run command: (This creates a node project in that folder that will have a package.json file.)
    npm init -y
    
  6. Run command: (This will install webdriverIO on the project)
    npm init wdio
    
  7. When prompted whether to continue or not. Type Y and press Enter.
  8. For "What type of testing would you like to do?". Select E2E Testing.
  9. For "Where is your automation backend located?". Select On my local machine
  10. For "Which type of environment would you like?". Select Web.
  11. For "With which browser should we start?". Select Chrome.
  12. Choose Mocha Framework for framework.
  13. For "Do you want to use a compiler?". Select No.
  14. Press Enter for the four commands to generate sample test cases and page object files.
  15. Choose spec reporter for test case reporting.
  16. For "Do you want to add plugins to your test setup?". Select wait-for.
  17. For "Do you want to add service to your test setup?". Navigate through the option and choose Appium using Spacebar and Press Enter.
  18. For "What is the base url?". Press Enter.
  19. When "Do you want me install npm install" is prompted. Press Enter.
  20. Wait for the command npm install to complete.
  21. After the setup is complete, a success message will be shown. Refer to the image below:
  22. The setup will install some directories and files on the project.
  23. Verify whether the wdio.conf.js file are created or not.
  24. There should be some sample test cases which were created during the setup. Verify the same in test/spec/ directory.

Configuration

Now, before running the test scripts we need to install several packages, configure the wdio.conf.js file. We also need to create env file so that the capabilities for different platforms can be added.

Install Dependencies

To install the required dependencies and configure package.json file, follow the steps given below:

  1. Run following commands in the terminal of the Code Editor (Make sure the path is set to your project directory. Refer Step 4 of the Project Setup section).
    • First, we need to install devtool package. It is used for DOM manipulation and network control. To know more, refer to this documentation by webdriver.io.
      npm install @wdio/devtools-service --save-dev
      
    • After this appium and appium service package is installed. These are used for mobile testing. Refer to this documentation by webdriver.io.
      npm install appium --save-dev
      npm install @wdio/appium-service --save-dev
      
    • Now, we need to install various drivers for mobile testing.
      npm install appium-chromium-driver appium-mac2-driver appium-safari-driver appium-uiautomator2-driver appium-xcuitest-driver --save-dev
      
    • Finally, run this command:
      npm install axios chalk cli-color cross-env ts-node typescript wdio-wait-for --save-dev
      
  2. In package.json file, replace the code in script with the below code:
    "scripts": {
        "wdio": "cross-env wdio run ./wdio.conf.js",
        "wdio debug": "cross-env NODE_WDIO_DEBUG=true wdio run ./wdio.conf.js",
        "wdio is_human": "cross-env NODE_WDIO_IS_HUMAN=true wdio run ./wdio.conf.js",
        "wdio mac": "cross-env NODE_WDIO_OS=mac wdio run ./wdio.conf.js",
        "wdio ios": "cross-env NODE_WDIO_OS=ios wdio run ./wdio.conf.js",
        "wdio windows": "cross-env NODE_WDIO_OS=windows wdio run ./wdio.conf.js",
        "wdio linux": "cross-env NODE_WDIO_OS=linux wdio run ./wdio.conf.js",
        "wdio android": "cross-env NODE_WDIO_OS=android wdio run ./wdio.conf.js"
    }
    
  3. Also add "type":"module" inside package.json file. Refer to the code below:
    ...
    "type": "module",
    "devDependencies": {
        ...
    }
    

Configure ENV file

  1. Create a new file in the root folder of the project, where the file wdio.conf.js file is located.
  2. Name the file wdio.env.js.
  3. Add the code given below inside the file:
    class Env {
        constructor() {
                this.params = {
                debug: false,
                is_human: true,
                is_human_pause: 1000,
                env: null,
                log_level: 'error',
                base_url: '',
                version: null,
                capabilities: [
                    {
                        platformName: "Linux",
                        "appium:automationName": "Chromium",
                        browserName: 'chrome',
                        acceptInsecureCerts: true,
                    }, 
                ]
            };
            if(process.env.NODE_WDIO_IS_HUMAN){
            this.params.is_human = true;
            }
            if(process.env.NODE_WDIO_DEBUG){
                this.params.debug = true;
            }
            if(process.env.NODE_WDIO_OS){
                this.setCapabilities()
            }
            if(this.params.debug === true){
                this.params.log_level = 'debug'
            }
        }
        //-------------------------------------------------
        setCapabilities(){
            switch(process.env.NODE_WDIO_OS){
                case 'mac':
                    this.params.capabilities = [
                        {
                            platformName: "mac",
                            "appium:automationName": "Chromium",
                            browserName: 'chrome',
                            acceptInsecureCerts: true,
                        }, {
                            platformName: "mac",
                            "appium:automationName": "Safari",
                            browserName: 'Safari'
                        }
                    ]
                break;
                case 'ios':
                    this.params.capabilities = [
                        {
                            platformName: 'iOS',
                            browserName: 'Safari',
                            'appium:platformVersion': '17.0',
                            'appium:automationName': 'XCUITest'
                        }
                    ]
            break;
                case 'android':
                    this.params.capabilities = [
                        {
                            platformName: 'Android',
                            browserName: 'Chrome',
                            acceptInsecureCerts: true,
                            "appium:deviceName": "P7A34", //this should match with emulator name
                            'appium:automationName': 'UIAutomator2',
                        }
                    ]
                    break;
                case 'windows':
                    this.params.capabilities = [
                        {
                            platformName: "Window",
                            "appium:automationName": "Chromium",
                            browserName: 'chrome',
                            acceptInsecureCerts: true,
                        }
                    ]
                    break;
                case 'linux':
                    this.params.capabilities = [
                        {
                            platformName: "Linux",
                            "appium:automationName": "Chromium",
                            browserName: 'chrome',
                            acceptInsecureCerts: true,
                        }
                    ]
                    break;
            }
        }
        //-------------------------------------------------
        getCapabilities(){
            let capabilities = this.params.capabilities;
            if(this.params.is_human === false){
    
                for(let i in capabilities)
                {
                    switch(capabilities[i].browserName)
                    {
                        case 'chrome':
                            capabilities[i]['goog:chromeOptions'] = {
                                args: [
                                    '--no-sandbox',
                                    '--disable-dev-shm-usage',
                                    '--disable-infobars',
                                    '--headless',
                                    '--disable-gpu',
                                    '--window-size=1440,735',
                                    '--disable-extensions'
                                ]
                            }
                        break;
                    }
                }
            }
            return capabilities;
        }
        //-------------------------------------------------
        getParams () {
            this.params.capabilities = this.getCapabilities();
    
            console.log('params-->', this.params);
    
            return this.params;
        }
    }
    export default Env;
    

Configure wdio.conf.js file

After this, we need to configure the wdio.conf.js file. Open the file and follow the steps mentioned below:

  1. Add the following code at the top of the file in order to import wdio.env.js file created in step 3 of Configure ENV File section.
    import env from "./wdio.env.js";
    const envObj = new env();
    const params = envObj.getParams();
    
  2. Replace exports.config to export const config. Refer to the code snippet below:
    export const config = {
        ...
    }
    
  3. Enter this code: env: params, inside exports.config. Refer to the code below:
    export const config = {
        env: params,
        //
        // ====================
        // Runner Configuration
        // ====================
        ...
    }
    
  4. For the capabilities replace the code with capabilities: params.capabilities,. Refer to the code below:
    export const config = {
        ...
        capabilities: params.capabilities,
        ...
    }
    
  5. Similarly replace the baseUrl with baseUrl: params.base_url,.
  6. Search for services inside "export const config". If it is not present add the code mentioned below. If it is present, replace the services with the below code.
    export const config= {
        ...
        services: [
            [
                'appium',
                {
                    args:{
                        allowInsecure: ['chromedriver_autodownload', 'adb_shell'],
                    }
                }
            ]
        ],
        ...
    }
    

Now, the configuration is completed. But we still need to do some changes with the test files before we can start running our script.

Configure test scripts

Follow the steps mentioned.

  1. Open the file login.page.js inside the directory test/pageobjects. Replace the "require" code at the top with the code given below:
    import { $ } from '@wdio/globals'
    import Page from './page.js'
    
    Also replace the module.exports = new LoginPage(); code at the bottom with export default new LoginPage();
  2. Open the file secure.page.js in the same directory. Do the same replacements.
  3. Open the file page.js. Replace the "class Page" with export default class Page. Refer to the code snippet below. Rest of the code inside Page class should remain unchanged.
    export default class Page{
        /**
        * Opens a sub page of the page
        * @param path path of the sub page (e.g. /path/to/page.html)
        */  
    }
    
    Also replace the const { browser } = require('@wdio/globals') with import { browser } from '@wdio/globals'.
  4. Finally open the file test.e2e.js in the directory test/specs. Replace the "require" codes with the code snippet below:
    import { expect } from '@wdio/globals'
    import LoginPage from '../pageobjects/login.page.js'
    import SecurePage from '../pageobjects/secure.page.js'
    

The configuration is now complete. You can start running the test scripts now.

Running the test script

  1. Before running the test script. We need to verify the path under the specs keyword in file wdio.conf.js.
  2. To run the test script, run command:
    npm run wdio
    
  3. After the test script ran successfully, a spec report will be generated. Refer to the image below:
  4. To run a specific test script: Run the command:
    npx wdio run wdio.conf.js --spec test1.js
    
  5. Once the sample test scripts are running successfully, you can modify and create your own scripts.

Mocha Framework

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.

First, install the adapter package from NPM:

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

After a successful installation of the mocha framework. Verify the package.json file the presence of mocha framework:

"@wdio/mocha-framework": "^8.16.12"

Advantages of Mocha

  1. Feasibility: Mocha is simple to install and get started with. It can be easily integrated into JavaScript projects, quickly incorporating testing into the development workflow.
  2. Versatility: Mocha can be used in browser and server-side environments, making it suitable for various JavaScript applications. Mocha can efficiently test code when developing a back-end server or front-end web application.
  3. Accuracy: Mocha generates detailed and accurate test reports, clearly indicating the success or failure of each test. Mocha provides informative error messages, and stack traces when a test fails, making it easier to pinpoint and debug issues in code.

To know more about the mocha framework refer to this documentation by mochajs.org


Copyright © 2024