WebDriver IO Architecture
WebdriverIO: WebdriverIO built on top of NodeJS which communicates with NodeJS.
WebdriverIO is a tool used to create automated browser tests.
NodeJS: NodeJS is an open-source project which helps to run the Javascript runtime environment.
Pre-requisites:
Node.js (https://nodejs.org/en/)
Follow the instructions for install. To check installation is successful, run
node -v in the terminal, you should see the Node version installed.
NPM ( https://www.npmjs.com/)
This will be installed with node. To check, run npm -v in the terminal, you should see the NPM version installed. If not installed, follow the instructions for install from the link above.
A text editor for Javascript
For example, Atom (https://atom.io/).
Java (https://www.java.com/en/download/).
Installed and added to your path (this is a requirement for Webdriverio).
How Flow works in WebDriverIO
JavaScript written by the user sends a request by WebdriverIO via nodeJS to the Services which is in the form of HTTP command using JSON Wire Protocol. Now, services forward the request to browsers to perform user actions.
The Following are the supported reporters’ examples:
Allure Reporter
Mochawesome Reporter
CucumberJS JSON Reporter
The following are an example of the supported services
Selenium Standalone Service
ChromeDriver Service
Docker Service
The followings are the test framework supports
Mocha
Jasmine
Cucumber
Why WebDriverIO
WebDriverIO framework is being widely used by the testing community to perform automation testing on both web applications and native mobile applications. The tests performed on WebdriverIO are simple and concise.
The Key Features of WebDriverIO:
Run automation tests both for web applications as well as native mobile apps
Simple and Easy Syntax
Integrating tests to third-party tools such as Appium.
‘Wdio setup wizard’ to make the setup simple and easy. (WDIO--> WebDriver IO Setup)
Integrated test runner
WebdriverIO has support for asynchronous commands, we don't need to write waits and all
WebDriverIO Vs Selenium WebDriver
Selenium is used for automating browsers, while WebDriverIO is used for automating both browsers and native mobile apps.
In Power Shell
mkdir WebDriverIOTutorials
cd WebDriverIOTutorials
Create an NPM project(package.json) (Package.json is just like your pom.xml)
by running below command on terminal
npm init -y
The -y is “Yes’. When you run the above command, it starts asking some questions and for those questions, you are saying Yes for all questions asked during initializing.
This will Create package.json file.
Sample Below Screenshot
Install WebdriverIO CLI
To install WebDriverIO CLI, execute the below command in the terminal.
npm i --save-dev @wdio/cli
I option is to install
–save-dev saves the dependencies in package.json so that if you share this project with a colleague, he/she need not repeat the same activity.
Now Package,json looks like below
Go to Location--> C:\Users\T460\Desktop\WebDriverIOTutorials\node_modules\.bin
Type below command
npm i webdriverio --save-dev (Install WebDriverIo)
./wdio config -y
Again -y is Yes and you are giving your consent to all prompts asked during the configuration process.
This command will create a “wdio.conf.js” javascript configuration file
You will see WebDriveIO dependencies installed
Note: Now you will see All dependencies downloaded in node_modules folder
Learn more about WebDriverIO CLI
https://webdriver.io/docs/clioptions/ (Very Good Resource)
Now Create Test case
Go to Location
C:\Users\T460\Desktop\WebDriverIOTutorials
Type Command
mkdir -p ./test/specs
Sample Script
const assert = require('assert')
describe('Bugreaper Blog page', () => {
it('should have the Correct Page title', () => {
browser.url('http://bugreaper.blogspot.com/')
const title = browser.getTitle()
assert.notStrictEqual(title, ' Bug Reaper')
})
})
Execute Test cases
Note: In above test case it() is coming from Mocha library
Run below command
PS C:\Users\T460\Desktop\WebDriverIOTutorials> ./node_modules/.bin/wdio run wdio.conf.js
? Error: Could not execute "run" due to missing configuration. Would you like to create one? Yes
Refer Below Screenshot
After Configuration is ready you will see something like below
Configuration file was created successfully!
To run your tests, execute:
$ npx wdio run wdio.conf.js
Now Run below command and you will see browser will launched
PS C:\Users\T460\Desktop\WebDriverIOTutorials> npx wdio run wdio.conf.js
Setup Allure Report
Run below command in PowerShell
npm install @wdio/allure-reporter --save-dev
Configuration
Configure the output directory in your wdio.conf.js file:
Note: change reporters: [spec] to below
reporters: [['allure', {
outputDir: 'allure-results',
}]],
Run the Test case
npx wdio run wdio.conf.js
Generate Allure Report
allure generate --clean allure-results
Open Allure Report
allure open
For more follow Blog
https://webdriver.io/docs/allure-reporter/
Install Chai (Chai provides assertion library for JS framework)
npm i --save-dev chai
Install WebDriverIO Chai
npm install chai-webdriverio --save-dev
Install Local-runner
npm i local-runner --save-dev
Sample Assertion
var chai=require("chai");
const { assert, expect } = require('chai');
expect(1,"It failed").to.be.equal(2);
Sample Chai Assertion
//chai asserstion
expect(browser.getUrl()).equals("https://www.freshworks.com/contact/","Looks like URL is incorrect");
How to Execute one Test class only
npx wdio run wdio.conf.js --spec sample.js (Here sample.js is our test class file)
Mocha has hooks
Go to wdio.conf.js
We will configure BeforeTest
Uncomment--> beforeTest--> Shortcut for Uncomment--> Ctrl+k+u
Shortcut for Comment--> Ctrl+k+c
/**
* Function to be executed before a test (in Mocha/Jasmine) starts.
*/
beforeTest: function () {
const chai=require('chai')
const chaiWebDriver=require('chai-webdriverio').default
chai.use(chaiWebDriver(browser))
global.assert=chai.assert
global.should=chai.should
global.expect=chai.expect
},
Note: "scripts" Section in package.json is like we have surefireplugin to run test
We can setup some basic things in wdio.conf.js
Sample Script
describe('Test Amazon', function(){
it("WebElements", function(){
browser.url('https://www.amazon.com/')
browser.pause(5000)
const search=$('#twotabsearchtextbox')
search.click()
browser.pause(2000)
search.setValue('Mac Book')
browser.pause(2000)
search.clearValue()
browser.pause(2000)
search.addValue('Mac Book Again')
browser.pause(2000)
console.log('Value-->'+search.getValue())
const logo=$('#nav-logo-sprites')
logo.waitForClickable({timeout:3000})
logo.click()
const signIn=$('#a-autoid-0-announce')
browser.waitUntil(()=> signIn.isClickable())
signIn.click()
browser.pause(5000)
})
})
BASEURL--> we can set in --> wdio.conf.js
Use below snippet and baseURL will be fetched from wdio.conf.js
browser.url(`${browser.options.baseUrl}`)
If you want to append URL next to BASE URL
browser.url(`${browser.options.baseUrl}/contact`)
browser.pause(5000)
How to Log in Console
console.log("Text here-->"+homePage.getChildElementText(1))
How to Press Keys
write a modular Helper Function
enterText(element,text){
element.setValue(text)
}
Below Snippet is example how to press Tab Key
homePage.enterText(homePage.firstName,"Tab")
OR
browser.keys("Tab")
Maximize Browser Window
browser.maximizeWindow()
ScrollPage using ScrollIntoView()
homePage.contactUs.scrollIntoView()
Select Value from Drop Down
homePage.queryType.selectByVisibleText("Support")
homePage.queryType.selectByIndex("2")
Print Values from Drop Down
Below Function to get list of Elements
get queryTypeList(){
return $$(".field-dropdown>select>option")
}
Below Function to print values from Drop Down
let listQuery=homePage.queryTypeList
console.log("List size-->"+listQuery.length)
for (let index = 0; index < listQuery.length; index++) {
console.log("List value-->"+listQuery[index].getText())
}
Select Element from Drop Down is there is no Select Tag in DOM
Below Function to get list of Elements
get queryTypeList(){
return $$(".field-dropdown>select>option")
}
Below Function to Select Desired values from Drop Down
homePage.queryType.selectByIndex("2")
let listQuery=homePage.queryTypeList
console.log("List size-->"+listQuery.length)
for (let index = 0; index < listQuery.length; index++) {
console.log("List value-->"+listQuery[index].getText())
if(listQuery[index].getText()=="Sales"){
listQuery[index].click()
break;
}
}
WaitForExist
Wait for an element (selected by css selector) for the provided amount of milliseconds to be present within the DOM.
homePage.deleteElement.waitForExist(5000)
Example
it("Add or Remove Elements",function(){
browser.url("https://the-internet.herokuapp.com/add_remove_elements/")
homePage.addElement.click()
homePage.deleteElement.waitForExist(5000)
assert.equal(true,homePage.deleteElement.isExisting(),"Not Existing")
})
How to MoveTo Element
homePage.moveToElement(homePage.supportLink)
Explicit Wait, wait Until Method
browser.waitUntil(function(){
return getStartedButton.isDisplayed()===true
}),6000, "Email is not displayed"
})
How to Create TestSuite Runner
Make an entry of suite block in wdio.conf,js
Same Entry we have to make in package.json
Example in wdio.conf.js
suites:{
testelements: [
'./test/elements/*.js'
]
},
Example in package.json
"scripts": {
"testelements": "node_modules/.bin/wdio wdio.conf.js --suite testelements",
},
Note: Here we have added "testelements" block in json files
The Path--> /test/elements/*.js (where our test scripts are present)
How To Run above suite from command line
Type
npm run --suite testelements
How to pass TestData in TestCases
Create a class example logindata.js
module.exports = {
username: 'Neeraj',
}
Now we will use this class
First define import the loginData.js file where you want to use this
const loginData=require("../testdata/logindata")
Use in Test Function
it("Enter Text and Tab KEY Event",function(){
browser.url(`${browser.options.baseUrl}`)
browser.pause(2000)
homePage.clickonContactUs();
browser.maximizeWindow()
browser.pause(2000)
homePage.enterTextinElement(homePage.firstName,loginData.username)
browser.keys("Tab")
browser.keys("Tab")
browser.pause(5000)
})
Retry Failed Test cases in WebDriverIO
describe("Home Page Element",function(){
this.retries(2)// This will retry the failed Test case
No comments:
Post a Comment