Cypress-if Plugin

Profile picture for user arilio666

In this article, we will use if-else conditional statements in Cypress with the help of a plugin. This plugin works by overriding get and find commands, but the same won't work for XPath.

1.) Installation

npm i -D cypress-if
  • Copy and paste this command into the vscode terminal to download the plugin.
import 'cypress-if'
  • Add this to the command.js file.

2.) Syntax

cy.get().if().else().finally()

3.) Example

For Example, we will be working on the programsbuzz site, where we will try to type in 'Cyss' instead of 'Cypress' in the search box.
We will use if, else, finally to validate whether the value matches with the correct one and ask it to type it correctly using a conditional statement.

describe('Automate AutoPract',()=>{
   it('Should load the url',()=>{
       cy.visit('https://www.programsbuzz.com/')
       cy.get('.fas.fa-search').click()
      cy.get('#edit-keys').type('Cyss')
   .if('not.have.value','Cypress')
   .clear().type('Cypress')
   .else()
   .log('has expected search text')
   .finally()
   .should('have.value','Cypress')
   })
})
  • We are first asking the if condition that if it does not have the value ' Cypress,' clear it and type 'Cypress' correctly.
  • Otherwise, log a message and finally assert whether it has value cypress if it is correct.
  • We can see that the plugin works by clearing and typing the correct word according to the condition and asserting in the end that it finally has the value.