Cypress
Cypress
What is Cypress?
Cypress is a purely JavaScript-based front-end testing tool built for
the modern web.
Why cypress?
It aims to address the pain points developers or QA engineers face while
testing an application. Cypress is a more developer-friendly tool that
uses a unique DOM manipulation technique and operates directly in the
browser. Cypress also provides a unique interactive test runner in which
it executes all commands.
Cypress Ecosystem:
Cypress consists of a free, open source, locally installed application
and Cypress Cloud for recording your tests.
First: Cypress helps you set up and start writing tests every day
while you build your application locally. TDD at its best!
Installing cypress:
We all know that cypress is a JavaScript based project so we have to
create the environment that should have JavaScript runtime environment
First of all we have to install nodeJs (Open source, backend
JavaScript runtime), (For window users it is recommended to
install .msi based on system configuration.)
Install VS code and then create the file Package.json (It will store
all your metadata helps to manage your project dependencies)
From this path we will hit npm install (node package manager)
whoever will developed software which is JavaScript based will
host all their package in npm
Likewise when u hit npm install command through package.Json it
will scan your package where u have given u need cypress 10.11 or
any other specific version and it automatically connects to its
repository.
Installing package.Json:
First open VS code click on left end and then open terminal.
Give command mkdir CypressAutomation. //mkdir is command
to open new file while cypressautomation is folder name.
After that give command cd CypressAutomation to navigate that
folder.
Then hit npm –I init to download package.Json.
After installing type yes.
Installing Cypress:
Again go to terminal of package.Json then install cypress using this
command.
npm install cypress --save-dev
Latest version of cypress is installed.
A folder called node-module is automatically created where all and
contain related dependencies
Opening cypress:
We use the code to open cypress:
npx cypress open
Choose testing type…
As a QA tester we will be focusing on end-to-end testing.
Here when we click on continue a folder name cypress.config.js
Choose a browser:
We can do testing in different browser
(Chrome, Edge, Firefox, Electron)
For electron (npx cypress run --headed)
For Chrome(npx cypress run –browser chrome)
First of all we will create a new folder named integration where we have
to write all our test cases.
{
it('my firstTest case',function(){
//all the test case is written inside it
})
LOCATORS:
Cypress only supports the Css selectors while other automation tools
like selenium use XPath, Css selectors and many others.
If we put # before id as #id it become Css selector.
If we put a dot before classname as .classname it is also a Css
selector. // remember there is no space in class name if there is any
put a dot there.
If we want a unique Css selector we will put tagname.classname or
tagname#idname.
You can also take any attribute and write Css selector for it as
tagname[attribute=value] // Tagname is always optional.
ASSERTIONS:
Cypress bundles the popular Chai assertion library, as well as helpful
extensions for Sinon and jQuery, bringing you dozens of powerful
assertions for free.
1. Should():
.should() is an assertion, and it is safe to chain further commands
that use the subject. ... Use Cypress commands before or after .should()
instead.
Syntax:
.should(chainers)
Example:
We have to assert checkbox is disabled.
Cy.get(‘.checkbox’).should(be.disabled)
2. And():
And is an alias of should().
Syntax:
.and(chainers)
Example:
Cy.get(‘.button’).should(‘have.active’,’class’).and(not.be.disabled)
Commands:
1) Cy.visit:
To visit a remote URL.
Cy.visit(url)
2) Cy.wait:
Wait for a number of milliseconds or wait for an aliased resource to
resolve before moving on to the next command.
Cy.wait(time)
3) Cy.wrap:
Yield the object passed into .wrap(). If the object is a promise, yield its
resolved value.
Cy.wrap(subject)
4) Cy.then:
Enables you to work with the subject yielded from the previous
5) Cy.pause:
Stop cy commands from running and allow interaction with the
application under test. You can then "resume" running all commands or
choose to step through the "next" commands from the Command Log.
It is unsafe to chain further commands that rely on a DOM element as
the subject after .pause().
Cy.pause()
6) Cy.go:
Navigate back or forward to the previous or next URL in the browser's
history.
Cy.go(direction)
Actions:
1. Type:
Type into a DOM element.
Cy.get(‘input’).type(text)
2. Select:
Select an <option> within a <select>.
Cy.go(‘input’).select(value)
3. Check:
Check checkbox(es) or radio(s).
Cy.get(‘input’).check()
4. Click:
Click a DOM element.
Cy.get(‘.btn’).click
Queries:
1. As:
Assign an alias for later use. Reference the alias later within
a cy.get() query or cy.wait() command with an @ prefix.
//.as(aliasname)
cy.get('.main-nav').find('li').first().as('firstNav')
2. Eq:
Get A DOM element at a specific index in an array of elements.
//.eq(index)
cy.get('tbody>tr').eq(0)
3. Filter:
Get the DOM elements that match a specific selector.
//.filter(selector)
cy.get('td').filter('.users')
4. Get:
Get one or more DOM elements by selector or alias.
//cy.get(selector)
cy.get('.list > li') // Yield the <li>'s in .list
5. Invoke:
Invoke a function on the previously yielded subject.
//.invoke(functionName)
cy.get('.input').invoke('val').should('eq', 'foo') // Invoke the 'val' function
6. Title:
Get the document.title property of the page that is currently active.
cy.title() // Yields the documents title as a string
7. Url:
Get the current URL of the page that is currently active.
cy.url()
This is an alias of cy.location(href).
Events:
Cypress emits a series of events as it runs in your browser. These events
are useful not only to control your application's behavior, but also for
debugging purposes.
Name: window:confirm
Yields: the confirmation text (String)
Fires when your app calls the
global window.confirm() method. Cypress will auto accept
Description:
confirmations. Return false from this event and the
confirmation will be canceled.
Event Details
Name: window:alert
Yields: the alert text (String)
Fires when your app calls the
Description: global window.alert() method. Cypress will auto accept
alerts. You cannot change this behavior.
Event Details
window:before:load
Name: End-to-End Only
//Dynamic Dropdown
cy.get('#autocomplete').type("ind")
Cypress Framework:
Here is a sample framework for automating a website.
Code Structure
Page Object Model
Importing Pages in Test Class
For Example in Below Example
Importing Home Page and Products Page inside Test Class
Importing Test data from Fixtures
Similarly as in Selenium we are following Page Object
Model here Importing Pages Inside Test Classes
/// <reference types="Cypress" />
import HomePage from'../../support/PageObjects/HomePage'
import products from'../../support/ProductsPage/products'
describe('My Second Test Suite', function()
{
before(function(){
cy.fixture("example").then(function(data)
{
this.data=data
})
// runs before all tests in the block
})
//we have to resolve the promise for the value that data returns
// this.data and data are different variables this.data is global
it('My FirstTest case',function() {
const homePage=new HomePage()
const Products=new products()
cy.visit(Cypress.env('url')+"/angularpractice/")
//This is example of subdomain means main domain is url itself while
subdomain which is angular paractice is concatenated with domain
// cy.visit('https://rahulshettyacademy.com/angularpractice/')
Cypress.config('pageLoadTimeout', 100000)
//for only one test case is we want to manage runtime
homePage.getEditBox().type(this.data.name)
homePage.getGender().select(this.data.gender)
homePage. getTwowaydatabinding().should('have.value',this.data.name)
homePage.getEditBox().should('have.attr','minlength','2')
homePage.getEnterprenuer().should('be.disabled')
//Cypress.config('pageLoadTimeout', 100000)
// for one specific click
homePage. getShopTab().click()
cy.SelectProduct(element)
});
Products.getcheckout().click()
var sum=0
cy.get('tr td:nth-child(4) strong').each(($el, index, $list) => {
const amount=$el.text()
var res=amount.split(" ")
res=res[1].trim()
sum=Number(sum)+Number(res)
}).then(function()
{
cy.log(sum)
})
cy.get('h3 strong').then(function(element){
const amount=element.text()
var res=amount.split(" ")
var total=res[1].trim()
expect(Number(total)).to.equal(sum)
})
cy.contains('Checkout').click()
cy.get('#country').type('India')
cy.get('.ng-untouched > .btn').click()
cy.get('#country').click({force:true})
cy.get('input[type="submit"]').click
cy.get('.alert').then(function(element)
{
const Actualtext=element.text()
expect(Actualtext.includes("Success")).to.be.true
})
})
})
For loop:
In for loop we initialize the variable, then satisfy the condition and then
increment or decrement of the variable is done.
for(let k=0;k>10;k++)
{
console.log(k)
}
console.log(marks.includes(98)) //false
Array can be cut into half or some digits are removed as:
console.log(marks.slice(2,5)) //[54,56,43]
Let suppose we want to sum all the elements of an array.
Var sum=0
for(let i=0;i<marks.length;i++)
{
sum=sum+marks[i]
}
Console.log(sum)
We can also sum all the values by using the Reduce Filter
method:
If you want to update or iterate the values reduce method is used.
let total=marks.reduce((sum,marks)=>sum+marks,0)
console.log(total)
If you want to filter your array according to the given condition.
let even=marks.filter(marks=>marks%2==0)
console.log(even)
Mapping is all about from mapping from one value to another
value. Filter only works when condition is satisfied.
let mappedarray=marks.filter(marks=>marks*3)
console.log(mappedarray)
Array can be sorted as:
marks.sort()
console.log(marks)
Sometimes it may throw errors while sorting as if we write 003 it
cannot be sorted correctly using this.
Then we will used the anonymous function to sort is as we use
reduce, filter and map.
console.log(marks.sort((a,b)=>a-b))
For reversing
marks.reverse()
console.log(marks)
//For strings this method works
For number data type:
console.log(marks.sort((a,b)=>b-a))
Functions in array:
Functions are the blocks of code.
The simple code for function in JavaScript is:
function add(a,b)
{
return a+b
}
let sum=add(2,3)
console.log(sum)
For anonymous functions (that do not have function name //
function expression)
let sumofintegers =function(c,d)
{
return c+d
}
To make our code more clear and simple we also remove
function keyword and code as:
let sumofintegers =(c,d)=> c+d
console.log(sumofintegers(2,3))
Strings in JavaScript:
Simple way to declare a string in JavaScript is:
let day='tuesday '
console.log(day.length) //8
here day.length shows the length of array.
If we want to remove some of letters we use slice method
let subday =day.slice(0,4)
console.log(subday)
To print on the specific index:
console.log(day[1])//1
To split the string:
let splitday =day.split("s")
console.log(splitday)
To convert string into number:
let date='23'
let nextdate ='27'
let diff=parseInt(nextdate)-parseInt(date)
console.log(diff)
To convert number into string:
let newquote=day+"is funday"
console.log(newquote)