【问题标题】:How to return a promise from a Cypress custom command in typescript?如何从打字稿中的赛普拉斯自定义命令返回承诺?
【发布时间】:2019-12-03 23:02:21
【问题描述】:

我正在将现有的自定义命令转换为 typescript,但遇到了问题。我的自定义命令返回一个Promise,赛普拉斯会自动处理并转换为Cypress.Chainable,但打字稿不知道这个魔法,所以它会抛出一个错误。这可能吗?有什么建议吗?

function test(): Cypress.Chainable<string> {
  return new Cypress.Promise<string>(resolve => {
    resolve("some data");
  });
}

Cypress.Commands.add("test", test);

给我:

[ts] Type 'Bluebird<string>' is missing the following properties from type 'Chainable<string>': and, as, blur, check, and 75 more.

我已经通过cy.wrap()将返回值转换为Cypress.Chainable,使用其他命令处理了这个问题,但我不知道如何使用Promise正确执行此操作:

function test(): Cypress.Chainable<string> {
  return new Cypress.Promise<string>(resolve => {
    resolve("some data");
  }).then(data => {
    return cy.wrap(data);
  });
}

给我:

[ts] Type 'Bluebird<Chainable<string>>' is missing the following properties from type 'Chainable<string>': and, as, blur, check, and 75 more.

或者如果我切换它:

function test(): Cypress.Chainable<string> {
  return cy.wrap(
    new Cypress.Promise<string>(resolve => {
      resolve("some data");
    })
  );
}

给我:

[ts]
Type 'Chainable<Bluebird<string>>' is not assignable to type 'Chainable<string>'.  Type 'Bluebird<string>' is not assignable to type 'string'.

【问题讨论】:

    标签: typescript cypress


    【解决方案1】:

    我找到了一个我现在正在使用的 hacky 解决方案,并在这里分享它以防它帮助任何人。我重构了执行回调的承诺,并正在等待定义该回调设置的值。我不会接受这个答案,因为必须有更接近原始问题的更好方法。

    function getData(successFn: (data: string) => void) {
      // do some work to get the data here
      successFn("some data");
    }
    
    function test(): Cypress.Chainable<string> {
      const start = Date.now();
      let toReturn: string | undefined;
      getData(data => { toReturn = data; }
    
      while (Date.now() < start + 5000) {
        if (toReturn) {
          return cy.wrap(toReturn);
        }
      }
    
      throw new Error("timed out waiting for data")
    }
    
    Cypress.Commands.add("test", test);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 2019-06-05
      相关资源
      最近更新 更多