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()
}
}
}
*/
=================================================================
| ## | Item | Description |
| 01 | Cypress Child widnow | Verify target is exist or not ? Open child in same window, by removing target attribute to child will open on same windiw |
| 02 | Target 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 |
| 03 | Invoke 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 |
| 04 | non fleaky test | consistent results from test using same browser |
| 05 | Browser back navigation go method | cy.go('back') cy.go('forward') cy.url().should('include', 'qaclickacademy') cy.go('back') |
| 06 | url method | url method to get the current url of the opened page cy,location('href') cy.url() cy.url(options) |
| 07 | include - substring assertion method | substring assertion to check whether string included or not cy.url().should('include', 'qaclickacademy') cy.go('back') |
| 08 | Web 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 |
| 09 | next() method | use this method on get() method in cypress |
| 10 | eq() method | eq method will use from array value grabbing we need to pass index to eq method to pull that index value |
| 11 | then() method | then method will be used to resolve current promise- and use the parameter to handle non cypress methods |
| 12 | expect() method | expect(price.toeqial('25') use expect method to compare expected and actual values |
| 13 | Mouse 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 |
| 14 | click() method for hidden element | cy.get('button').click({force: true}) We need to use force true when you want Cypress to click on hidden element |
| 15 | Open new windiw handle | copy 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 |
| 16 | get 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 |
| 17 | cy.log(url) | will log url value in test runner |
| 18 | Cypress restricts to visit one domain to another domain | |
| 19 | Handling FRAMES in Cypress | /// <reference types="Cypress-iframe" /> import 'cypress-iframe' cy.iframe().find("a[href*='mentorship'").eq(0).click() |
| 20 | Setting up test hooks | |
| 21 | Data Driven test | From FIXTURES folder -cypress will get data from external files 1 JSON file for 1 test case and use for execution |
| 22 | Custom Cypress commands | Support> commands folder to save and reuse functions into the tests |
| 23 | Parameterization | Tell 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) }); |
| 24 | Debug 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 |
| 25 | POM 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 |
| 26 | Directory 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 |
| 27 | Config changes Cypress.json | timeout 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 |
| 28 | Screenshots & video path | |
| 29 | Cypress Dashboard | |
| 30 | Global Environment Variables | global 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 |
| 31 | Reporting for execution | |
| 32 | Integrate Cypress with CICD | |
| 33 | Assertion for PASS & Fail | cy.get('.alert').then(function(element) { const actualtext=element.text() expect(actualText.includes("Success")).to.be.true expect(actualText.includes("Success")).to.be.false }) |
| 34 | split() 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 |
| 35 | convert strig to Number in JS | sum=Number(sum)+Number(result) |
| 36 | Cypress.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 |
| 37 | Cypress run in chrome cmd | cypress run -browser chrome cypress run -b chrome cypress run -b chrome -headed |
| 38 | Cucumber with Cypress | github 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()) } |
| 39 | inform cypress about feature files - command in | you need to tell cypress to pick feature files to execute,, "testFiles": "**/*.feature", |
| 40 | Downlod plugin for cucumber feature files | visual 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 |
| 41 | steps plugin | examples>BDD>ecommStepDef.js craete step def file.. import {Given, When,Then} from "cypress-cucumner-preprocessor/steps"; add this |
| 42 | annonymous function - FAT OPERATOR | we can change function() to ananymous function as ()=> when a function donn't havve name Mocha not supports this fat operator [IMP] |
| 43 | hooks in stepDef | Examples>BDD>ecommerce> beforeEach.js craete hook file -supports mocha related hooks |
| 44 | come out of sub folders | ../../../../support/pageObjects/HomePage' '../../../../support/pageObjects/ProductPage' each ../ means one sub folder. |
| 45 | Run cucumber feature file | cypress run --spec cypress\integration\examples\BDD\ecommerce.feature --headed --browser chrome |
| 46 | Data Driven Test in Cucumber | function(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 |
| 47 | variable 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 |
| 48 | Tagging for sceanrios/ tagged test s | @Regression ' @Smoke Scenario |
| 49 | npx -use to shorten command | node_modules\\.bin this is equal npx cypress-tags run -e TAGS="@Smoke" --headed --browser chrome |
| 50 | cucumber.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 |
| 51 | Xml http Request. API testing with Cypress | XHR 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.. |
| 52 | cy.server() | start server to begin routing responses to .. route is - Initiation of server command to listen API calls |
| 53 | cy.route() for GET method | helps to manage the behaviour of network request. cy.route('GET', 'comments/*') as (;getCommnet') |
| 54 | cyprus its method -to get a property value on the previously got value.. its('status') | cy.wait(@getComment').its('status').should('eq', 200) |
| 55 | POST 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()') |
| 56 | Mock/Mimic API calls using Cypress | Mock 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 .. |
| 57 | Stubbing response | cy.server() cy.route() |
| 58 | requet method -without using uI | explicitely hitting the server method.. resolve the promise and extract the response for validation.. |
| 59 | Cypress Request documentation | https://docs.cypress.io/api/commands/request.html#Syntax https://docs.cypress.io/api/commands/request#Method-and-URL |
| 60 | SQL database connection with Cypress | Cloud 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 .. |
| 61 | VS Editor- create empty folder CypressDB | Go 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 |
| 62 | Cypress 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') |
| 63 | Create DB test file | Go to integration -- create a new file .. |
No comments:
Post a Comment