Enhanced Test Automation with WebdriverIO

Book description

Elevate your testing game to the next level using advanced techniques and proven strategies with this book for WebdriverIO beginners and automation pros alike

Key Features

  • Improve your coding skills and empower your automation journey
  • Leverage self-healing objects and adaptive frameworks for cutting-edge WebdriverIO automation
  • Overcome script stability challenges and ensure robust, dependable test execution
  • Purchase of the print or Kindle book includes a free PDF eBook

Book Description

This book helps you embark on a comprehensive journey to master the art of WebdriverIO automation, from installation through to advanced framework development.

You’ll start by following step-by-step instructions on installing WebdriverIO, configuring Node packages, and creating a simple test. Here you’ll gain an understanding of the mechanics while also learning to add reporting and screen captures to your test results to enhance your test case documentation. In the next set of chapters, you’ll delve into the intricacies of configuring and developing robust method wrappers, a crucial skill for supporting multiple test suites. The book goes beyond the basics, exploring testing techniques tailored for Jenkins as well as LambdaTest cloud environments. As you progress, you’ll gain a deep understanding of both TypeScript and JavaScript languages and acquire versatile coding skills.

By the end of this book, you’ll have developed the expertise to construct a sophisticated test automation framework capable of executing an entire suite of tests using WebdriverIO in either TypeScript or JavaScript, as well as excel in your test automation endeavors and deliver reliable, efficient testing solutions.

What you will learn

  • Discover techniques to efficiently maintain and enhance your Page Object Model, saving time and effort
  • Gain insight into diagnosing and resolving script instability issues to ensure reliable test execution
  • Improve test resilience by building objects that adapt to changing element locators
  • Enhance your testing productivity by learning to write effective test cases with TypeScript
  • Explore strategies for comprehensive result analysis to enable data-driven decision-making
  • Develop frameworks that adapt to evolving user journeys, ensuring long-term test sustainability

Who this book is for

Whether you are a novice software development engineer in test (SDET) joining your first WebdriverIO automation project building test cases in TypeScript, or a seasoned lead framework architect experienced in solutioning daily test automation challenges, this book is for you. This book will also help developers and framework architects with basic knowledge of JavaScript or TypeScript who are looking to gain expertise in functional frontend testing. A basic understanding of CSS and XPath will help you get the most out of this book.

Table of contents

  1. Enhanced Test Automation with WebdriverIO
  2. Foreword
  3. Contributors
  4. About the authors
  5. About the reviewers
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Conventions used
    6. Get in touch
    7. Share Your Thoughts
    8. Download a free PDF copy of this book
  7. Chapter 1: The Utility Belt – Tools Every Superhero SDET Needs
    1. Virgin machine setup
    2. Rule of thumb – the hardware resources and access rights must match the development team
      1. Installing Node.js and npm
      2. Alternate node package managers – Yarn versus npm
      3. Configuring the coding environment with GitHub Desktop
      4. GitHub and the GitHub Desktop tool
      5. Getting a GitHub account
      6. Installing GitHub Desktop
      7. Choosing your TypeScript development environment – Microsoft Visual Studio Code versus JetBrains Aqua
    3. Installing Visual Studio Code for your operating system
      1. Initializing the Node project
      2. Configuring Visual Studio Code
    4. X-ray vision – writing better code with Prettier, ESLint, and GitLens
      1. Installing Visual Studio Code add-ons – Prettier
      2. Installing Visual Studio Code add-ons – GitLens
      3. Installing Visual Studio Code add-ons – ESLint
    5. Installing Chrome extensions
      1. Adding the SelectorsHub Chrome extension
      2. Adding the EditThisCookie Chrome extension
      3. Pinning Chrome extensions to the browser title bar
    6. Installing WebdriverIO
    7. Summary
  8. Chapter 2: Fortress of Solitude – Configuring WebdriverIO
    1. WebdriverIO setup
      1. Option 1 – cloning WebdriverIO from a boilerplate project
    2. Building and installing the project dependencies
      1. Making our first commit
    3. Summary
  9. Chapter 3: Cybernetic Enhancements – WebdriverIO Config and Debug Tips
    1. The three main files of a WebdriverIO node project
      1. The package.json file
      2. The yarn.lock file
      3. The wdio.conf.ts file and webhooks
    2. Rule of thumb – match your developer’s hardware
    3. Letting Yarn help keep files up to date
    4. Configuring debugging with VS Code
      1. browser.debug()
    5. Dynamic configuration
      1. A note about template strings
      2. Reducing the signal-to-noise ratio
    6. Our first custom wrapper method – global.log()
    7. Rules to enforce coding standards
      1. Strict mode
      2. Turning on individual TypeScript subset rule checks
      3. CodeGPT
    8. Summary
  10. Chapter 4: Super Speed – Time-Travel Paradoxes and Broken Promises
    1. Technical requirements
    2. The time-travel dilemma
    3. Schrödinger and the quantum mechanics of test automation
    4. Callbacks, promises, and async/await
    5. The death of fibers and synchronous mode
      1. Keep it simple with async and await
    6. Summary
  11. Chapter 5: Alter Egos – The ClickAdv Wrapper
    1. Adding a helpers file
    2. The “Hello, World!” of test automation
    3. ES6 helper modules versus overriding intrinsic methods
      1. Overriding intrinsic element methods
      2. Adding a custom element method
    4. Who tests the SDET’s code? Sanity testing of the automation framework
    5. Extending our ES module helper file with a custom click method
    6. Why are waits difficult to implement correctly?
      1. “I don’t always use Pause(), but when I do, It’s less than 1000 milliseconds”
      2. Highlighting elements
    7. Expanding the click method wrapper
    8. Supercharged scroll before a click event
    9. Expanding the click method wrapper
    10. The importance of metrics
    11. Self-healing elements
    12. Stubbing out methods with the “alreadyFailed” switchboard key
    13. Summary
  12. Chapter 6: The setValue Wrapper – Entering Text and Dynamic Data Replacement
    1. Normalizing the element type
    2. Adding the setValue() method wrapper
    3. Is this trip really necessary?
    4. Coal into diamonds – replacing dynamic data tags
    5. Injecting versus typing text into a field
    6. Checking whether the field is pre-populated for speed
    7. Behind the mask – SetValuePassword() to keep data secure
      1. Detecting and masking passwords in your output
    8. Putting it all together
    9. Summary
  13. Chapter 7: The Select Wrapper – Choosing Values in Lists and Comboboxes
    1. Adding the base functionality of clickAdv() and setValueAdv() to selectAdv()
    2. Selecting an item from the list
    3. Selecting from a combobox
      1. Using selectByVisibleText
      2. Using selectByAttribute
      3. Using selectByIndex
    4. Inspecting a list that closes when it loses focus with SelectorsHub
    5. Writing a locator that is an element inside a list
    6. Summary
  14. Chapter 8: The Assert Wrapper – the Importance of Embedded Details
    1. expect, assert, and should –how did we get here?
      1. What is Jasmine?
      2. What is Jest?
      3. What is Chai?
    2. Timeout – delay of game
      1. What is expect-webdriverio?
    3. What are hard and soft expect assertions?
      1. Putting it all together
      2. What are soft assertions and why would we need them?
      3. Soft asserts – allowing a test to continue after an assertion fails
    4. Introduction to Allure reports
    5. Summary
  15. Chapter 9: The Ancient Spell Book – Building the Page Object Model
    1. Technical requirements
    2. What is Page Object Model?
    3. What constitutes a good Page Object pattern?
    4. Creating a page class for the tests
    5. Adding object selectors
      1. // LoginPage.ts
      2. // HomePage.ts
    6. module.exports = new HomePage();Calling methods to be used in the test
      1. // TestName.ts
    7. Reducing code with common objects and methods
    8. POM using Klassi-js
      1. Project structure
      2. Cucumber feature files
      3. Page objects
      4. Cucumber step definitions
      5. Running tests
    9. Summary
  16. Chapter 10: Increased Flexibility – Writing Robust Selectors and Reducing Maintenance
    1. Technical requirements
    2. Reducing page object maintenance with generic selectors
    3. Anatomy of an XPath selector
      1. Relative selectors
      2. Node test functions – text() versus normalize-space()
      3. Broken strings
    4. Leveraging data-qa and ARIA attributes
      1. Finding an element only by text
    5. Writing an XPath element that contains a textual substring
      1. Finding an element relative to another element
      2. Case-insensitive partial matches
      3. Finding only visible elements
    6. Second chances – getting valid objects from stale selectors
      1. Self healing techniques
      2. On thin ice
    7. Summary
  17. Chapter 11: Echo Location – Skipping the Page Object Model
    1. A reduced code base
    2. Automation in plain English
      1. Getting a named button
      2. Getting a named input field
      3. Getting a named list
    3. Getting a visible button by name
    4. Getting a visible field by name
    5. Getting a visible list by name
    6. Getting a visible element from a collection
    7. Beware the endless rabbit hole!
    8. Summary
  18. Chapter 12: Superhero Landing – Setting Up Flexible Navigation Options
    1. Technical requirements
    2. Using system variables
    3. Adding data configuration files
      1. Where data is stored for test use
      2. Organizing test data
      3. Setting up TypeScript configuration
      4. Reading data from files
      5. Using test data in tests
      6. Beyond masking – making confidential data invisible
      7. Spec and Allure – cub reporter versus star journalist
    4. Configuring Allure reporting
      1. Adding custom comments to the Allure report
      2. Webhooks and screen captures
    5. Summary
  19. Chapter 13: The Multiverses – Cross-Browser Testing and Cross-Environment Testing
    1. Horizontal scaling – cross-browser testing
    2. Using built-in functionality via the wdio config file
      1. Extending the wdio config file so that it supports multiple browsers
      2. Handling browser-specific issues
      3. Test responsiveness
    3. Using LambdaTest online to automate the browser testing grid
      1. Live interactive testing
      2. Automated screenshot testing
    4. Using Selenium Standalone server to locally build the testing grid
      1. Cross-environment testing with a shared configuration file
    5. Avoiding the rabbit hole of horizontal scaling
    6. Handling environment-specific logic
    7. The multiverse – one test, two environments
    8. Summary
  20. Chapter 14: The Time-Traveler’s Dilemma – State-Driven End to End User Journeys
    1. Technical requirements
    2. Divide and conquer!
    3. Simplifying the complexities of a dynamic journey
    4. The happy path
      1. The big driver loop
      2. It’s all in the details
    5. Changing decision points
    6. Wash, rinse, repeat
    7. Why not generate these Artifacts with API calls?
    8. Summary
  21. Chapter 15: The Sentient Cape – Running Tests in a CI/CD Pipeline with Jenkins and LambdaTest
    1. Technical requirements
    2. What are Jenkins and Slack?
    3. Installing OpenJDK for Jenkins
    4. Installing Jenkins as a standalone application
    5. Installing Jenkins
    6. Creating a WebdriverIO project with Jenkins
    7. Installing the Jenkins plugin for LambdaTest
      1. Configuring LambdaTest using Jenkins
    8. Creating a freestyle project and job
      1. Parameterizing
    9. Reporting in Slack from Jenkins
      1. Adding the Slack notifications plugin to Jenkins
      2. Adding the Jenkins CI app to Slack
      3. Adding the post-build Slack action
    10. On-demand and scheduled suite runs
    11. Types of debugging runs with Jenkins
      1. Additional suite categories
      2. Linking Allure reports to a Jenkins run
    12. CI/CD pipeline
      1. What is continuous testing?
      2. What does a CI/CD pipeline look like?
      3. Code repository
      4. CI
      5. Artifact generation
      6. Deployment
      7. CD
      8. Continuous feedback
      9. Jenkins for CI/CD
    13. Summary
  22. Appendix: The Ultimate Guide to TypeScript Error Messages, Causes, and Solutions
    1. Problem: Install default WDIO settings by passing “--yes” parameter still asks configuration questions
    2. Problem: Missing script “wdio”
    3. Problem: “node : The term ‘node’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.”
    4. Problem: ‘wdio’ is not recognized as an internal or external command”
    5. Problems:
    6. Problem: The \node_modules folder is not created when installed in a new WDIO project folder.
    7. Problem: New project install fails with empty directory.
    8. Problem: Tests suddenly fail to run including the \specs\test.e2e.ts. sample test.
    9. Problem: “WARN webdriver: Request encountered a stale element - terminating request”
    10. Problem: “TypeError: elem[prop] is not a function”
    11. Problem: Statements execute out of order
    12. Problem: “ERROR @wdio/runner: Error: describe expects a function argument; received [object AsyncFunction]”
    13. Problem: “Unsupported engine”
    14. Problem: JavaScript Debug Terminal skips breakpoints
    15. Problem: Browser launches and locks up
    16. Problem: “SevereServiceError: Couldn’t start Chromedriver: timeout. Please check if port [<PortNumber>] is in use”
    17. This is how to do it using macOS: lsof -i :<PortNumber> : kill -9 <PID>
    18. Problem: MODULE_NOT_FOUND
    19. Problem: Error: Could not execute “run” due to missing configuration, file “C:\repos\wdio\test\wdio.conf.ts” not found! Would you like to create one?
    20. Problem: “report does not exist” when running an Allure report
    21. Problem: “[P]lugin “allure” reporter, neither as wdio scoped package “@wdio/allure-reporter” nor as community package “wdio-allure-reporter”. Please make sure you have it installed!”
    22. Problem: TypeError: Cannot read properties of undefined (reading ‘open’)
    23. Problem: Cannot read properties of undefined (reading ‘setWindowSize’)
    24. Problem: A service failed in the ‘onPrepare’ hookSevereServiceError: Couldn’t start Chromedriver: timeout. Please check if port 9515 is in use!
    25. Problem: “Cannot find name ‘describe’” and underlined in red
    26. Problem: “Cannot find name ‘it’”
    27. Problem: “Cannot find name ‘expect’. Do you need to install type definitions for a test runner?” but the test still runs.
    28. Problem: “An import path can only end with a ‘.ts’ extension when ‘allowImportingTsExtensions’ is enabled.ts(5097)”
    29. Problem: browser.debug() generates “Failed to read descriptor from node connection: A device attached to the system is not functioning.”
    30. Problem: Element implicitly has an ‘any’ type because type ‘typeof globalThis’ has no index signature
    31. Problem: Cannot find type definition file for ‘jasmine’
    32. Problem: “Execution of 0 workers” No tests get executed.
    33. Problems: Cannot find name ‘browser’ and Cannot find name ‘$’
    34. Problem: Property ‘toBeExisting’ does not exist on type
    35. Problem: ERR! [Error: EACCES: permission denied (Mac OSX)
    36. Problem: ERROR @wdio/selenium-standalone-service: Error: not found: java
    37. Problem: “ECONNREFUSED 127.0.0.1:9515” a service failed in the ‘onPrepare’ hook tcp-port-used
    38. Problem: Error: Cannot find module ‘C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js’
    39. Problem: “Note: Package.json must be actual JSON, not just JavaScript”
    40. Problem: Protocol error (Runtime.callFunctionOn) target closed
    41. Problem: “unexpected token” in tsconfig.json
    42. Problem: “TypeError: elem[prop] is not a function”
    43. Problem: “ServerServiceError in “onPrepare” Cannot find package ‘chromedriver’
    44. Problem: Property ‘{functionName}’ does not exist on type ‘({functionType<{argName>}) => void’
    45. Problem “Property ‘addCommand’ does not exist on type ‘Browser’.” (macOS)
    46. Problem: ConfigParser: pattern ./test/specs/**/*.ts did not match any file.
    47. Problem: Error: Timeout - Async function did not complete within 10000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
    48. Problem: Error: Error: Couldn’t find page handle
    49. Problem: This expression is not callable. Type ‘void’ has no call signatures.ts Are you missing a semicolon?
    50. Problem: “File is not a module”
    51. Problem: “Couldn’t find page handle”
    52. Problem: “Error: {pageName} is not defined”
    53. Problem: Argument of type ‘ChainablePromiseElement<Element>’ is not assignable to parameter of type ‘Element’.
    54. Problem: Unable to delete or modify files or folders in the WebdriverIO project
    55. Problem: EJSONPARSE Unexpected token in JSON while parsing Failed to parse JSON data
    56. Problem: A long string of gibberish garbage characters is added to the wdio.config.ts file when running in JavaScript Debug Terminal in Windows
    57. Yarn and Node Package Manager (npm), Node Version Manager (nvm), and Node Package Executor (npx) Shell command cheat sheet
    58. Reference links
  23. Epilogue
  24. Index
    1. Why subscribe?
  25. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts
    3. Download a free PDF copy of this book

Product information

  • Title: Enhanced Test Automation with WebdriverIO
  • Author(s): Paul M. Grossman, Larry C. Goddard
  • Release date: November 2023
  • Publisher(s): Packt Publishing
  • ISBN: 9781837630189