Conditional testing with Cypress :
In this article we will see how to do a conditional testing, i.e. check if a content exists and if not do something else instead of throwing a test failure.
let’s say for example that you would like to test your application’s research engine. To do so, you get the search box, type two words in it and then type enter.
//get and type in the search box two key words
typeSearchWords() { cy.get(searchElements.searchBox).type("shirt" + " " +"man"));}}
The expected event is to have a product grid containing elements with at least one of the searched words in their description. To write that into code we need to use the Jquery function find. This function returns a collection with a length corresponding to the number of matching queries.
(Note : there is a method find() in cypress too, but it is not the one we are using below, because that one returns the content of a selector or if not found an error)
checkProducts() {cy.get(searchElements.productGrid).then((body) => {if(body.find('span:contains(shirt).length > 0){ expect(body).to.be.ok}
else if(body.find(men).length > 0) { expect(body).to.be.ok}
else {throw new Error("couldn't find the seached queries")}})}
Above, we tried to find the word “shirt” within the <span> selectors in the productGrid part. if the length of the array returned by the find function is superior to 0 then the word was found, if not we proceed with research of the second word. If it was not found neither, then the test should fail, since none of the products have the queries researched.