4

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

});
halfer
  • 19,824
  • 17
  • 99
  • 186
Devmix
  • 1,599
  • 5
  • 36
  • 73
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Taplar Jul 29 '20 at 18:09
  • 2
    You can't return values like that in cypress. Did you try using aliases? – Muditha Perera Jul 29 '20 at 18:55

1 Answers1

6

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
})
k.vincent
  • 3,743
  • 8
  • 37
  • 74