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

4

我很难从我的自定义函数中返回一个值,因为我正在处理一个Promise。

这是我的代码:

这是我的自定义函数:

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 
   }

});

这是我的测试套件:

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

});

这个回答解决了你的问题吗?如何从异步调用中返回响应? - Taplar
2
你不能在Cypress中像那样返回值。你尝试使用别名了吗? - Muditha Perera
1个回答

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

1
我已经尝试过这个,但是我的代码从来没有进入“then”部分。 - Janpan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接