skip to Main Content

I have 2 tests:

First:
Login-> Go to page A-> click on a checkbox A -> click on button A – >do an action.

Second:
Login -> Go to page A-> click on a checkbox A -> click on Button B -> do an action.

Since Login, Go to page A and click on checkbox A are identical steps..
IS there a way i can write these two tests in the same command instead of writing two different commands.

Thank you

2

Answers


  1. You can use Cypress’ beforeEach() functionality to execute a set of commands before each test runs.

    describe('My tests', () => {
      beforeEach(() => {
        // login
        // go to page A
        // click checkbox A
      });
    
      it('clicks button A', () => {
        // click button A
        // other actions
      });
    
      it('clicks button B', () => {
        // clicks button B
        // other actions
      });
    });
    

    This is most useful when running the same tests in a shared describe or context block.

    If your tests will be in separate describe/context blocks or in separate spec files, you may want to consider creating a Cypress custom command to be re-used in different files.

    Cypress.Commands.add('myFunction', () => {
      // login
      // go to Page A
      // click checkbox A
    });
    
    describe('My First Tests', () => {
      it('clicks button A', () => {
        cy.myFunction();
        // click button A
        // other actions
      });
    });
    
    describe('My Second Tests', () => {
      it('clicks button B', () => {
        cy.myFunction()
        // clicks button B
        // other actions
      });
    });
    
    Login or Signup to reply.
  2. The command can take parameters to change it’s test sequence as required.

    With parameters you can compose the command to suit different parts of the test.

    Cypress.Commands.add('customTestSequence'), (buttonSelector, actions) => {
    
      cy.visit('pageA')             // fixed step
      cy.get('checkboxA').check()   // fixed step
    
      // variable steps
      cy.get(buttonSelector)        
      cy.then(() => {               // put actions call inside .then for correct sequence
        actions()
      })
    })
    
    cy.customTestSequence('buttonB', () => {
      // actions in this callback can be js functions or further Cypress commands
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search