Search code examples
javascriptjquerycypressautotest

How to creat command in Cypress


In debugging my Cypress tests I use a command for highlighting the element I am currently working with

{CurrentElement}.then($el=> {$el.css('border', '1px solid magenta')})

I'd like to create something more informative and short. So I am looking towards the custom command in commands.js. But I was not succed doing this. I was trying to creat custom command in commands.js:

Cypress.Commands.add("highlight", $el=> {$el.css('border', '1px solid magenta')})

And then to use it in my test in this way:

{CurrentElement}.then(highlight())

or like this:

{CurrentElement}.then(highlight($el))

But anytime I get ReferenceError: highlight is not defined. How can I implement the working command for this?


Solution

  • In order to use the syntax:

    {CurrentElement}.then(highlight($el))

    you don't need a custom command. Just declare highlight as a normal function.

    However, using a custom command you will be able to write it as follows:

    {CurrentElement}.highlight();

    which IMHO is more elegant.

    In order to do so, you need to specify that the command should be applied on an element subject, as follows:

    Cypress.Commands.add("highlight", {prevSubject: 'element'}, $el=> {$el.css('border', '1px solid magenta')});