Devmix
Devmix

Reputation: 1858

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

});

Upvotes: 4

Views: 10083

Answers (1)

Verònica Jandrew
Verònica Jandrew

Reputation: 462

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

Upvotes: 6

Related Questions