Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a value from custom function in Cypress?

I've been struggling with returning a value from my custom function due to the fact that I'm dealing with a promise.

Here's my code:

This is my custom function:

Cypress.Commands.add("myFunction", () => {
   cy.get('#someID').then($container) => {
      const isHidden = $container().children('div:nth-child(3)').is(':hidden');
      console.log(isHidden); // This returns either true or false and that is good  
      return isHidden; // this returns $chainer but I want to return either true or false 
   }

});

Here is my test suite:

context('some description', () => {
  before(function(){
      const result = cy.myFunction();
      console.log(result); // This is $chainer, but I want to get the value of true or false from isHidden variable 
  });

});
like image 979
Devmix Avatar asked Oct 25 '25 04:10

Devmix


1 Answers

I am doing this with cy.wrap (see https://docs.cypress.io/api/commands/wrap/#Syntax) which returns a Cypress.Chainable that allows you to use then with the result.

Cypress.Commands.add('myFunction', () => {
    return cy.wrap('myResult');
})

cy.myFunction.then((text) => {
    console.log(text); // myResult
})
like image 71
Verònica Jandrew Avatar answered Oct 26 '25 16:10

Verònica Jandrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!