如何从 Cypress 中的自定义函数返回值?

pro*_*ogx 4 javascript promise cypress

由于我正在处理承诺,因此我一直在努力从自定义函数返回值。

这是我的代码:

这是我的自定义函数:

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 
   }

});
Run Code Online (Sandbox Code Playgroud)

这是我的测试套件:

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

});
Run Code Online (Sandbox Code Playgroud)

小智 6

我正在这样做cy.wrap(请参阅https://docs.cypress.io/api/commands/wrap/#Syntax),它返回一个 Cypress.Chainable ,允许您使用then结果。

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

cy.myFunction.then((text) => {
    console.log(text); // myResult
})
Run Code Online (Sandbox Code Playgroud)