cypresscypress-custom-commands

Cypress: wrap chained commands in one


I use this long line to check the selected value on any list on my page (using Ember power-select which is not a but a complex set of ), selector being the parent so I can target the list I want, and trimming being there so I can chain a .should('eq', expected_value)

cy.get(selector).find('span[class="ember-power-select-selected-item"]').invoke("text").then((text) => text.trim())

I would love to shorten all the commands after get in one, and be able to call something like

cy.get(selector).selected_value()

I've started reading on custom commands, wrap, invoke... but am too new on Cypress to understand the right way to do this.


Solution

  • To add a custom command, you may add the following inside cypress/support/commands.js file:

    Cypress.Commands.add('selected_value', { prevSubject: true}, (subject) => {
      return cy.wrap(subject).find('span[class="ember-power-select-selected-item"]').invoke("text").then((text) => text.trim())
    })
    

    Note that we use the prevSubject option to be able to chain our command from an initial cy.get(selector) one.

    And now you are able to use the command:

       cy.get(selector).selected_value().should('eq', expected_value)
    

    Also, it's better to provide a type script definition file for the new command so IDE can be aware of it and provide the autocomplete and other features.

    Adding a command might look a bit complicated for a beginner or annoying for an experienced user. There is Cypress Pro plugin (I'm the author) for the IntelliJ platform that can simplify creating and maintaining custom commands.