0
votes

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?

2

2 Answers

1
votes

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')});

0
votes

you should refer to highlight() as cy.highlight() since it is a method chained of cy. So it would look like this:

Commands.js

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

spec.js

{CurrentElement}.then(cy.highlight())