Thursday, 29 April 2021

Cypress Library

CYPRESS LIBRARY: 

package MavenTestNG;


public class A1CypressTutorial {


public static void main(String[] args) {

}

}


/*

IMP URL's

Learn JS from here

https://developer.mozilla.org/en-US/docs/Web/JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Assertions: https://docs.cypress.io/guides/references/assertions.html#Chai


Test Websites:



//1)CYPRESS PROGRAM==HANDLING WEB TABLE DATA===============

/// <reference types="Cypress" />

describe('My Second Test Suite', function() 

{

it('My FirstTest case',function() {

//Check boxes

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

//grab the nth required column value and get value from array index:

cy.get('tr td:nth-child(2)').each(($e1, index, $list) => {

     const text=$e1.text()

    if(text.includes("Python"))

    {

         cy.get("tr td:nth-child(2)").eq(index).next().then(function(price)

        {

         const priceText=   price.text()

         expect(priceText).to.equal('26')

        })

    }

 })

 })

 })

//2)CYPRESS PROGRAM==HANDLING CHILD WINDOW LINKS ==============

describe('My Second Test Suite', function() 

{

it('My FirstTest case',function() {

//Check boxes

cy.visit("http://qaclickacademy.com/practice.php")

cy.get('#alertbtn').click()

cy.get('[value="Confirm"]').click()

//window:alert

cy.on('window:alert',(str)=>

{

//Mocha FW-compare strings: expect(str1).to.equal(str2)

expect(str).to.equal('Hello , share this practice page and share your knowledge')

})

cy.on('window:confirm',(str)=>

{

//Mocha

expect(str).to.equal('Hello , Are you sure you want to confirm?')

})

//Opening child window from the same browser by removing target link in DOM

cy.get('#opentab').invoke('removeAttr','target').click()

//String attribute assertion and then apply browser back button 

cy.url().should('include','qaclickacademy')

cy.go('back')

}  )


}  )

//3)CYPRESS PROGRAM==HANDLING HIDDEN LINKS==============

// <reference types="Cypress" />

 

describe('My Second Test Suite', function() 

it('My FirstTest case',function() {

//Check boxes

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

//cy.get('div.mouse-hover-content').invoke('show')

cy.contains('Top').click({force: true})

cy.url().should('include','top')

})

})


//4)CYPRESS PROGRAM==HANDLING FRAMES==============

/// <reference types="Cypress" />

/// <reference types="Cypress-iframe" />

import 'cypress-iframe' //this will import cypress libraries


// npm install -D cypress-iframe (this command will download iframe related libraries and supports for IFrames)

 

describe('My Second Test Suite', function() 

it('My FirstTest case',function() {

//Iframe window and assertions (text and count assertions), always mention cy.Iframe if you want actions on iframe

cy.visit("https://rahulshettyacademy.com/AutomationPractice/")

cy.iframe().find("a[href*='mentorship'").eq(0).click()

cy.iframe().find("h1[class*='pricing-title'").should(have.ength', 2]

})

})


//4)CYPRESS HOOK (Annnotations)

 https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests.html#hooks

before -It should be outside of it block, inside describe block

after- 

beforeEach- before of each test case (it block)

afterEach-

 

//5)CYPRESS commands to store all custom/reusable functions

//Command.js to store reusable function in JSON (eg=SelectProduct function)

no need to create object etc..

 Cypress/Commands.add("SelectProduct", (productName) => {

 cy.get('h4.card-title').each($e1, index, $list) => {

  if($e1.text().includes(productName))

  {

  cy.get('button.btn.btn-info').eq(index).click()

  }

 }

 }


 */



=================================================================

##ItemDescription
01Cypress Child widnowVerify target is exist or not ?
Open child in same window, by removing target attribute to child will open on same windiw
02Target attribute
target='_blank'
Cypress having ability to manipulate the DOM-so we can  remove target attribute:
manipulate DOM to handle to open in same window
 
qaclickacademy.com
03Invoke Method Invoke Method will invokes function on previoulsy used method
cy.get('#opentab').invoke('removeattr', 'target').click()
Here after the link will open on same browser instead of opening in new windiw
04non fleaky testconsistent results from test using same browser 
05Browser back navigation
go method
cy.go('back')
cy.go('forward')
cy.url().should('include', 'qaclickacademy')
cy.go('back')
06url methodurl method to get the current url of the opened page
cy,location('href')
cy.url()
cy.url(options) 
07include - substring assertion methodsubstring assertion to check whether string included or not
cy.url().should('include', 'qaclickacademy')
cy.go('back')
08Web table handling Web table handling
https://rahulshettyacademy.com/AutomationPractice
cy.visit("url")
CSS selector to select all columns in table
tr- rows
td- columns
nth child CSS= tr td:nth-child(2) //this will give 2nd column
Write css for all columns, iterate columns to get required values, then pgrab nex t row value using index and apply next method,. resolve promise and capture expected value 
09next() methoduse this method on get() method in cypress
10eq() methodeq method will use from array value grabbing
we need to pass index to eq method to pull that index value
11then() methodthen method will be used to resolve current promise- and use the parameter to handle non cypress methods
12expect() methodexpect(price.toeqial('25')
use expect method to compare expected and actual values
13Mouse over on menu
Show() method
actions in Selenium,  no specific method in Cypress.
Jquery function to trigger mouse over - show() method can be used
move to that element and apply mouse over using show method to display hidden elements
Show method should be applied on immediate parent of hidden element 
14click() method for hidden elementcy.get('button').click({force: true})
We need to use force true when you want Cypress to click on hidden element 
15Open new windiw handlecopy new window url(using href attribute) and open on same browser to work on new windiw
Else remove target from DOM to use current browser to open link
16get attribute value
prop() jquery method
jQuery method to get the value of the property
use then function to resolve promise and use Jquery method to get property
17cy.log(url)will log url value in test runner
18Cypress restricts to visit one domain to another domain 
19Handling FRAMES in Cypress/// <reference types="Cypress-iframe" />
import 'cypress-iframe'
cy.iframe().find("a[href*='mentorship'").eq(0).click()
20Setting up test hooks
21Data Driven testFrom FIXTURES folder -cypress will get data from external files
1 JSON file for 1 test case and use for execution
22Custom Cypress commandsSupport> commands folder to save and reuse functions into the tests
23ParameterizationTell to JSON prodname is as Array to store multiple values ..  put fixtures as before hook
JS treats [] as array  productName":["nokia", "voda"]
how to iterate array in JS?
this.data.productName.forEach(function(element){
cy.selectProduct(element)
});
24Debug tests/ pause test
debug()
cy.pause()
cy.pause() method use to pause your test, resume button from test runner will continue the test
we can use debug() method also at end of step line to debug code
25POM design pattern
Create JS class for each page under Integration folder and export , import from classes 
Collect objects of page and update in 1 JS class..
INtegration folder> HomePage.js
class HomePage
{
getEditBox()
{ return cy.get('#test')  //this return is mandatory to return to object
}
getGender()
{
}
export default Homepage; //will available in all classes with this line
26Directory and creating objects from custom class../ (this will bring current directory) ; ../pageObjects/HomePage eg:
import HomePage from ' ../pageObjects/HomePage'
Create object in JS  ---> const homePage= new HomePage()
homePage.getEditBoac().type(this.data.name)  //using webelement from homePage class POM
27Config changes Cypress.jsontimeout can be updated from Cypress.json - global wait/timout
If you want to handle in specific class- we can update timeout config to that class only
28Screenshots & video path
29Cypress Dashboard
30Global Environment Variablesglobal variables declared to access for all test cases like url, username, env etc..
Global variables exposed by Cypress from cypress.json file
Global customer variables by user created - into another Cypress.json file
cy.visit(Cypress.env('url'))  --> this will bring actual url from global va from cypress.json
31Reporting for execution
32Integrate Cypress with CICD
33Assertion for PASS & Failcy.get('.alert').then(function(element)
{
const actualtext=element.text()
expect(actualText.includes("Success")).to.be.true
expect(actualText.includes("Success")).to.be.false

})
34split() method from the string (r. 50000) splits before and after space from e. 50000
var result= actualText(split(" ")
result[1].trim()
r. 50000 this will be split into 2 below in array indexes
result[0]= R.
results[1]=50000

car sum=0
sum=Sum+result
35convert strig to Number in JSsum=Number(sum)+Number(result)
36Cypress.env('url')
CLI command line interface
to get gloabl variable from cypress.json file which is created by custom variable
CLI method to update url:
cypress run
cypress run
PS C:users\rahul\projects\auto> node_modules\.bin\cypress run  --> TO RUN ALL TESTS
37Cypress run in chrome cmdcypress run -browser chrome
cypress run -b chrome
cypress run -b chrome -headed
38Cucumber with Cypressgithub page.. https://github.com/TheBrainFamily
 https://github.com/TheBrainFamily/cypress-cucumber-preprocessor
Install this plugin for your cypress..  package.json will hae an entry
npm install --save dev cypress-cucumber-preprocessor
Add cucumber preprocessor command into the plugins/index.js file
const cucumber = require('cypress-cucumber-preprocessor').default
module.exports = (on, config) => {
on('file:preprocessor', cucmber())
}
39inform cypress about feature files - command in you need to tell cypress to pick feature files to execute,,
"testFiles": "**/*.feature",
40Downlod plugin for cucumber feature filesvisual studio bdd extension ..
Cucumber(Gherkin) Full support plugin..
eCommerce.feature create file..
examples>BDD>eCommerce.feature
Feature: End to End E-commerce validation

application Regression
Scenario: eCommerce prod delivery
Given on Ecommerce web page
When adding items to the Cart
And validate the total pricess and submit
Then verify the success message on submission.
Then 
41steps pluginexamples>BDD>ecommStepDef.js craete step def file..
import {Given, When,Then} from "cypress-cucumner-preprocessor/steps";  add this 
42annonymous function - FAT OPERATORwe can change function() to ananymous function as ()=> when a function donn't havve name
Mocha not supports this fat operator [IMP]
43hooks in stepDefExamples>BDD>ecommerce> beforeEach.js   craete hook file -supports mocha related hooks 
44come out of sub folders ../../../../support/pageObjects/HomePage'
'../../../../support/pageObjects/ProductPage'   each ../ means one sub folder.
45Run cucumber feature filecypress run --spec cypress\integration\examples\BDD\ecommerce.feature --headed --browser chrome
46Data Driven Test in Cucumberfunction(dataTable) will bring feature file data into stepDef .js file
dataTable.rawTable[1]  -first row will be trieved,
dataTable.rawTable[1][0] this will give first col value from first row- nem value
dataTable.rawTable[1][1] this will give second col value from first row- nem value 
47variable inside function and global declaration
let method
let name = dataTable.rawTable[1][0] this will accessed within block/function
if you declare at global level, then it will accessible from all classes..
let name = this can accessible in all functions/blocks
48Tagging for sceanrios/ tagged test s @Regression
 ' @Smoke
Scenario                                                                                         
49npx  -use to shorten commandnode_modules\\.bin  this is equal
npx cypress-tags run -e TAGS="@Smoke" --headed --browser chrome
50cucumber.json outfile from cucumber-json folder will be created .this file is output of all feature files execution results
We need to add additional json object to the package.json file.. it will generates json file in outFolder..
so now use other plugin to read json output file and create html dahsboard report
STEP1- install plugin into yourframework.. npm install multiple-cucumber-html-reporter --save-dev  [this will add plugin into package.json file]
STEP-2  under proj create folder named as  cucumber-html-report.js and paste content - that wil create html report .
cucumber2.js js file will go and read output json file and creates cucumber dashboard report
STEP3 enter jsonDir path value.. cucumber.json path
reportPath - value
STPE 4- run this js file?  node cucumner-html-report.js
STEP 5- goto reports folde and open index.html report
51Xml http Request. API testing with CypressXHR test :is an api/XHR object to send data from abrowser to web server as response..
kitchensink application  -test api website..
https://example.cypress.io/commands/querying
https://example.cypress.io/commands/network-requests
F12--> Network Tab -- XHR tab- select row -- header , preiew , repsonse, Timing..
52cy.server()start server to begin routing responses to ..
route is  - Initiation of server command to listen API calls
53cy.route() for GET methodhelps to manage the behaviour of network request.
cy.route('GET', 'comments/*') as (;getCommnet')
54cyprus its method -to get a property value on the previously got value..
its('status')
cy.wait(@getComment').its('status').should('eq', 200)
55POST method// Listen to POST to comments
cy.intercept('POST', '**/comments').as('postComment')
// we have code that posts a comment when
// the button is clicked in scripts.js
cy.get('.network-post').click()
cy.wait('@postComment').should(({ request, response }) => {
  expect(request.body).to.include('email')
  expect(request.headers).to.have.property('content-type')
  expect(response && response.body).to.have.property('name', 'Using POST in cy.intercept()')
56Mock/Mimic API calls using CypressMock service response to replicate the issue/or to capture error / error handling scenario..
Cypress will inject the fake response to browser - 404 -then expected exception handling can be tested ..
57Stubbing responsecy.server()
cy.route()
58requet method -without using uIexplicitely hitting the server method..
resolve the promise and extract the response for validation..
59Cypress Request documentationhttps://docs.cypress.io/api/commands/request.html#Syntax
https://docs.cypress.io/api/commands/request#Method-and-URL
60SQL database connection with CypressCloud SQL server to connect and get data and connect with Cypress
SQL server on Azure.. Start Free account .. create MS account and login..
Azure Sign on form, entetr credit card details.. for 1.5 month free and ask for renew..

Create Resourece, Slect Create SQL database.. enter DB name rahulacademy ..create new Server .. rsademo..
take few min to setup..
Go to Query Eiditor--> Add IP address into firewall rule to query..
Set server Firewall -- Add clinet IP - save and retry login
Home page -select DB and select query Editor and login..
Create New EMP table using DB query..  and click RUN..
insert records intp EMP table..
Retrieve records from table using query..
DB server, Database, Table, records have been craeted ..



61VS Editor- create empty folder CypressDBGo to Terminal, enter command
nps cypress -save-dev  [to install and creates cypress project to start working on it]
INvoke cypress dash board using
go to path of node modules..
./node_modules/.bin/cypress opn  OR use below simple command to open cypress
npx cypress open 
62Cypress DB plugin integration for DB testing.bring cypress sql jars..
npm install --save-dev cypress-sql-server
should have package.json and download dependencies.. for easy use..
npm init -y  [it will create package.json file and all dependencies will be brought into it]
https://www.npmjs.com/package/cypress-sql-server
initialise plugin into cypress index.js file,so plugin will be initialised..
go to index.js file and enter below lines..
const sqlServer = require('cypress-sql-server');

module.exports = (on, config) => {
  tasks = sqlServer.loadDBPlugin(config.db);
  on('task', tasks);
}
Go to support.index.js file and use bellow lines..
import sqlServer from 'cypress-sql-server';
sqlServer.loadDBCommands();

Go to cypress.json and add below AZURE DB details..:
"db": {
    "userName": "",
    "password": "",
    "server": "",
    "options": {
        "database": "",
        "encrypt": true,
        "rowCollectionOnRequestCompletion" : true
    }
}

Go to Index.js file and add below config details to connect with DB server details.
const dbConfig = require('../../cypress.json')
63Create DB test fileGo to integration -- create a new file ..



No comments:

Post a Comment