Cypress comes with its own API which allows users to create or override an existing cypress command. The interesting part is that we don't have to import anything as when the Test runner open these files are automatically loaded or Imported.
If you wondering how to define custom command then it is very easy as we create our Cypress project it automatically creates a spec file named command.js inside a folder named support.
By default you will find several samples of command commented inside this spec file. In this post we will show how to use custom commands in our spec files
Find the screenshot below where it is showed the Support and command.js spec file contained in it.
To demonstrate the power of custom command we will visit a site and login into it using Cypress Commands. The site we will visit is https://www.saucedemo.com/ and we will pass the following user name : standard_user and password : secret_sauce to login into it.
Inorder for us to do it we will create a custom command named UserLogin which will type username, password and click login button. These all will be done when we call the Cypress command UserLogin on our main spec file.
CODE : command.js
/// <reference types = "Cypress" />
describe('Customized Commands',function(){
context('Test Cases',function(){
it('Test 01',function(){
cy.visit('https://www.saucedemo.com/')
cy.UserLogin()
})
})
})
CODE : Customized commands.js
Cypress.Commands.add("UserLogin",()=> {
cy.get('[data-test=username]').type("standard_user")
cy.get('[data-test=password]').type("secret_sauce")
cy.get('.btn_action').click()
})
EXPLANATION
UU
The below is the execution output video,
Download the spec file below,
command.js : https://drive.google.com/open?id=1v37Xy1GgGZvTu0lS1jTQJ7eyumT4zdOB
Customized commands.js : https://drive.google.com/open?id=1aDk-J-eoBGhEcD2rfUZ3Avy_21lquWxJ