Cypress: Parsing through search suggestion text box with Jquery

While writing test script, it might be very difficult for us to get the text from text suggestion box and click the text. Since in Cypress we cannot assign the text value of a tag directly, it becomes more difficult for us to assert and select particular text from the suggested text. For this issue, we will use Jquery to parse through the suggested text and click on the apt one.

Pre-requisite:

  • npm

Let’s get started:

First thing will be initializing the empty node package manager(npm) with below command after creating a project folder,

npm init -y

Now we may need to install the testing framework Cypress with below command,

npm install cypress

Let’s open the Cypress with below command,

npx cypress open

Test scenario:

Our scenario will be typing “javascript” inside the google search bar and then selecting “javascript basics” from the suggestion bar,

Google search for javascript

Let’s code:

Open your own IDE and select the folder where you have configured cypress. Create a new test script inside the integration folder by defining describe and it block,

describe('Google search selector',()=>{it('Parsing the Google suggested text',()=>{})
})

Now, we will visit the google web page and type “javascript” inside the search bar with below commands,

//Visiting the Google search enginecy.visit('www.google.com')//Selecting and typing over the search barcy.get('[name=q],[type=text]').type('javascript')

As we type in the search box, we will get the text suggestion below. We need a selector to get all the text suggestion. I found a below command which could get all the text selector,

cy.get('.sbct > div > div > div > span')

Parsing through the suggested texts:

So, its time to parse through the suggested text with the .each() function provided by Jquery and check whether each text has “javascript basics” in it,

//Looping through the suggested elementscy.get('.sbct > div > div > div > span').each(($suggestions)=>{//Searching the perfect suggestion in the suggestion barif($suggestions.text()=="javascript basics")

Selecting the text:

Once we found out the exact text, let’s click over the text using .trigger() function provided by Jquery,

$suggestions.trigger('click')

Final code:

Our final code will look like below,

completed test case

That’s it! We are done with the test case!

--

--

Programmer who loves to do things creatively. #automationTester by profession #javascript #nodejs #reactjs

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Siddharth Murugan

Programmer who loves to do things creatively. #automationTester by profession #javascript #nodejs #reactjs