How to check if an element exists or not using Cypress?

ronikakashyap1 38 views 11 slides Nov 22, 2024
Slide 1
Slide 1 of 11
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11

About This Presentation

Cypress is a tool that helps web developers and testers to make sure their websites work properly. It can check if a certain part of the website exists.


Slide Content

TestInfrastructure&End-to-EndTestingCloud
Howtocheckifanelement
existsornotusingCypress?

Cypressisatoolthathelpswebdevelopersandtesterstomakesure
theirwebsitesworkproperly.Itcancheckifacertainpartofthe
websiteexists.Thisishelpfulbecauseithelpstocatchproblems
beforeusersdo.Elementpresenceisoneofthefirstthingsyoushould
testwithCypressinyourproject.Inthisarticle,wewilllookathowto
testifanelementexistsornot.Also,ifitexists,howdoyoucheck
whetheritisvisibleornot?.
WhatareCypressElements?
●ElementsinwebapplicationsrefertoindividualHTMLelements
thatmakeupawebpage’sstructureandcontent.
●Examplesofelementsincludebuttons,textboxes,links,and
images,eachwiththeirownattributeslikeid,class,andstyle.
●TheseattributescanbeusedtointeractwithCSSorJavaScript
selectors.
●Elementsareimportantbecausetheydefineapage’sstructure
andbehavior.
●Byselectingandinteractingwithelements,youcancreate
automatedteststoensurethatthewebapplicationbehavesas
expectedforallusers.

●InCypress,elementsaretheHTMLelementsofyourwebsite
thatyouwishtointeractwithortest.
●Tointeractwithortesttheseelements,simplyselectthemusing
aselectorsimilartoCSS.
WhyElementExistenceMattersin
Cypress?
Awebsiteislikeapuzzlewithinteractivepiecessuchasbuttonsand
forms.Testinginvolvesensuringthatthesepiecesareinthecorrect
placeandfunctioningproperly.Checkingifanelementexistsis
importantbecausedifferentpartsofawebsitecanchangebasedon
useractions.
Forinstance,a“Submit”buttonmayappearafterfillingoutaform,so
it’snecessarytocheckifitshowedup.Thishelpsidentifyissues
beforeusersencounterthem,allowingforsmootherexperiences.

HowtoVerifytheexistenceofan
elementusingCypress?
Cypressprovidesseveralmethodstoverifytheexistenceofelements
onawebpage.Let’sdiveintoeachapproachandunderstandhowto
implementthemeffectively.
1.cy.get()Method
Thecy.get()methodinCypressisusedtoselectandretrieveelements
onthepagebasedonvariousselectorssuchasclassnames,IDs,
attributes,andmore.Toverifyifanelementexists,developerscanuse
theshould()commandalongwiththecy.get()method.
Usingthe.should(‘exist’)assertionwithcy.get()ensuresthatthe
selectedelementispresentonthepage.

2.cy.contains()Method
Thecy.contains()methodisusedtofindanelementbasedonitstext
content.Thismethodcanalsobeutilizedtocheckifanelementwith
specific textexistsonthepage.
3.cy.find()Method
Thecy.find()methodisusefulwhendealingwithnestedelements
withinaparentelement.Itallowsyoutosearchforelementswithin
thecontextofanotherelement,ensuringmorefocusedsearches.

4.cy.get().should()withCustomAssertions
Cypressenablesdeveloperstocreatecustomassertionsusingthe
cy.should()method.Thisisparticularlyusefulwhenyouwantto
implementmorespecific checksbeyondjustelementexistence.
5.Using.should()withTimeout
Sometimes,elementsmightloadasynchronouslyorwithaslight
delay.Insuchcases,youcanusethe.should()assertionwitha
timeouttoensurethatCypresswaitsfortheelementtoappear.

ConditionalTestingwithCypress:
ConditionaltestinginCypressistheactofintegratingconditional
logicintoyourtestscriptstomakedecisionsandperformactions
basedonspecific conditionsoroutcomesduringthetestexecution.
Thismethodenablesyoutodesignmoreflexibleandadaptabletests
thatcanhandlevariousscenariosandrespondaccordingly.Cypress
offersarangeofcommandsandAPIsthatyoucanutilizetoachieve
effectiveconditionaltesting.Thefollowingisanillustrationofhow
Cypresscanbeusedforconditionaltesting.
Example-1

Inthisexample,thetestscriptvisitsawebpageandperforms
conditionaltestingonanelement’sexistenceaswellasthetitleofthe
page.Dependingonwhethertheconditionsaremetornot,thescript
logscorrespondingmessagestotheCypresstestingrunner’soutput.
Cypressprovidesafluentandintuitivesyntaxforperforming
conditionaltestingwithinyourtestscripts.Youcanuseassertions,
promises,andregularJavaScriptlogictobuildcomplexconditions
andactionsbasedontheresultsofthoseconditions.
ConditionaltestinginCypress,similartoothertestingframeworks,
helpsyoucreatemoreversatileandeffectiveteststhatcanadaptto

differentscenarios,makingyourtestingprocessmorerobustand
reliable.
Example2:
Inthiscodesnippet,Cypressfirstensurestheexistenceofthebutton
elementusing.should(‘exist’).Itthenretrievestheelementusing
.then(),andthesubsequentconditionalcheckdetermineswhetherthe
buttonexists.Iftheconditionismet,indicatingthebutton’spresence,
Cypressclicksthebuttonusingcy.wrap(button).click().Ifthecondition
fails,theelseblockfacilitatestheexecutionofanalternativeaction.
Real-WorldApplicationsofElementExistenceChecks:

Let’sthinkaboutsomeeverydaysituationswherecheckingelement
existenceissuperhelpful:
1.FormSuccessMessage
Afteruserssubmitaform,asuccessmessagemightappear.Using
Cypress,youcancheckifthatmessageshowsup,makingsureusers
knowtheirformwassubmittedsuccessfully.
2.MenuNavigation
Youhaveadropdownmenuthatappearswhenusershoverovera
button.Youwanttoconfirm thatthemenuappearswhenusersdo
thathoveraction.
3.ResponsiveDesign
Differentelementsmightappearordisappearonmobileversus
desktopversionsofyoursite.YoucanuseCypresstoensurethat
theseelementsshowuporhideasintended.
4.UserAccessControl

Certainbuttonsorlinksmightonlybevisibletocertaintypesofusers.
Cypresshelpsyouverifythattheseelementsareshowntotheright
people.
Conclusion:
Webtestingisnolongeradifficultandtime-consumingtask,thanksto
toolslikeCypress.The“ifelementexists”capabilityencapsulatesthe
essenceofconditionaltesting,enablingdevelopersandtestersto
craftteststhatcloselymimicrealuserinteractions.Thisfunctionality
notonlysimplifies testingbutalsoencouragesamorethoughtful
approachtoapplicationbehaviour.ByleveragingCypress’sintuitive
commandsandpowerfulassertions,developerscanstreamlinetheir
testsuites,reduceredundancy,andbuildmorerobustweb
applications.So,embracethepowerofCypressandembarkona
journeytoelevatethequalityofyourwebdevelopmentprojects.
Source:Thisblogwasoriginallypublishedat
https://testgrid.io/blog/how-to-check-if-an-element-exists-or-not-using-
cypress/