【问题标题】:returning Cypress.Promise from a Cypress command breaks types从 Cypress 命令返回 Cypress.Promise 会破坏类型
【发布时间】:2021-12-03 17:50:46
【问题描述】:

以下 Cypress 命令在 Cypress 8.x.x 中编译

declare global {
  namespace Cypress {
    interface Chainable<Subject> {
      login(): Chainable<Token>;
    }
  }
}
Cypress.Commands.add('login', () => {
  return new Cypress.Promise((resolve, reject) => {
    // rest
  });
});

但升级到 Cypress 9.x.x 后,我收到以下 TypeScript 错误:

argument of type '() => Bluebird<unknown>' is not assignable to parameter of type '(person?: Partial<Person>) => Chainable<Token>'.
  Type 'Bluebird<unknown>' is missing the following properties from type 'Chainable<Token>': and, as, blur, check, and 83 more.ts(2345)

【问题讨论】:

  • 请问Token是什么类型的?

标签: typescript cypress


【解决方案1】:

问题在于实现与输入不匹配:实际返回的值 (new Cypress.Promise(…)) 是一个承诺,或者更严格地说是 PromiseLike,但不是 Token1 .

由于 Cypress 使用 Bluebird Promise,为了匹配实现,login() 的返回类型也必须是 bluebird Promise;你可以像这样从 Cypress 包中导入符号:

import type Bluebird from "cypress/types/bluebird";

declare global {
    namespace Cypress {
        interface Chainable {
            login(): Bluebird<Token>;
        }
    }
}

Try it2.

1 – FWIW,OP 没有透露 Token 是什么,所以从技术上讲它可以是 PromiseLike,在这种情况下我的回答是没用的,但 IMO 这不太可能。无论如何,用户@PeaceAndQuiet 的相应问题被忽略了,所以我必须假设Token 不是PromiseLike(可能是访问令牌)。

2 – 请注意,cypress 可能出于某种原因不会被操场“拾取”;它是 npm 安装的(转到插件 → 向下滚动)

【讨论】:

    【解决方案2】:

    9.0.0 中有一些重大更改。 见changelog for 9.0.0 可能影响您的是从上数第 6 个。 它是一个地址功能17496

    你应该用可以接受 bluebird 承诺的东西替换 &lt;Token&gt;。或者将其设置为&lt;any&gt;

    declare global {
      namespace Cypress {
        interface Chainable<Subject> {
          login(): Chainable<any>;
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      TypeScript 错误是由于版本 9.0.0 中的重大更改造成的。见 changelog

      自定义命令实现现在基于声明的自定义可链接对象进行类型化。地址#17496

      这意味着现在您在实现中的返回值必须与声明的类型/自定义链式匹配。

      在您的情况下,在实现中您将返回 Bluebird promise:

      return new Cypress.Promise((resolve, reject) => { ... });
      

      您现在应该更新您的打字界面以匹配类型,可以是:

      declare global {
        namespace Cypress {
          interface Chainable {
            login(): Cypress.Promise<Token>;
          }
        }
      }
      

      或者,按照@Dima Parzhitsky 的建议:

      import type Bluebird from 'cypress/types/bluebird';
      
      declare global {
        namespace Cypress {
          interface Chainable {
            login(): Bluebird<Token>;
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        • 2022-01-27
        相关资源
        最近更新 更多