【问题标题】:TS2339: Property 'username' does not exist on type 'JQuery<HTMLElement>'. When using Cypress fixturesTS2339:“JQuery<HTMLElement>”类型上不存在属性“用户名”。使用赛普拉斯灯具时
【发布时间】:2021-08-11 09:24:29
【问题描述】:

我是使用 TypeScript 的新手,我正在尝试将我的 Cypress 测试转换为 TS,但每当我从固定文件中读取时都会遇到问题,例如出现错误。

TS2339:“JQuery”类型上不存在属性“用户名”。

我收到错误的一个例子是:

 cy.fixture("details").as("details");

    cy.get("@details").then((users) => {
      const user: string = users.username;

如果我让任何类型的用户例如,我可以让它运行

.then((用户:任意)

但我知道这不是解决问题的好方法。

我看到其他几个问题也有类似的错误,但我不确定如何让这些解决方案与赛普拉斯一起使用,有人可以提出任何可能有帮助的建议吗?

【问题讨论】:

    标签: jquery typescript cypress


    【解决方案1】:

    首先,您必须为您的用户结构定义一个类型,如下所示:

    class User {
      username: string
    }
    

    之后,您可以在请求别名值时引用此类型(注意 get 表达式):

        cy.get<User>("@details").then((users) => {
              const user = users.username;
        }
    
    

    【讨论】:

    • 请问除了检查类型定义来源之外,您从哪里获得此信息?它有效,我只是想知道他们网站上除了官方 API 定义之外是否有任何文档 - 因为没有任何关于 as&lt;T&gt;() 接口的说明。
    • 我确实从类型定义源获得了这个信息(只是因为我怀疑它应该在那里)。如果对背景知识感兴趣,可以参考TS泛型话题:typescriptlang.org/docs/handbook/2/generics.html
    【解决方案2】:

    cypress.d.ts 中有interface Chainable 包含get(alias) 语法的此定义

    /**
     * Get one or more DOM elements by alias.
     * @see https://on.cypress.io/get#Alias
     * @example
     *    // Get the aliased ‘todos’ elements
     *    cy.get('ul#todos').as('todos')
     *    //...hack hack hack...
     *    //later retrieve the todos
     *    cy.get('@todos')
     */
    get<S = any>(alias: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<S>
    

    由于某种原因,它没有在测试中出现,但您可以对其进行修补

    /// <reference types="cypress" />
    
    // Add type definition in test file or /cypress/support/index.ts
    declare namespace Cypress {
      interface Chainable {
        get<S = any>(alias: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<S>
      }
    }
    
    it('sees the get(alias) type def', () => {
    
      cy.fixture("example").as("details")   // using example fixture installed by Cypress
    
      cy.get("@details").then((user) => {
        const name: string = user.name  // no error
        const email: string = user.email  // no error
      })
    })
    

    如果您只想键入一个通用对象,请使用Cypress.ObjectLike,在cypress.d.ts 中定义为

    interface ObjectLike {
      [key: string]: any
    }
    

    在测试中用作

    /// <reference types="cypress" />
    
    cy.get<Cypress.ObjectLike>("@details").then((user) => {
      const name: string = user.username;
    })
    

    注意
    别名的赛普拉斯 dfn 具有通用类型 get&lt;S = any&gt;,因此您的解决方案 .then((users: any) =&gt; 几乎是等效的。

    【讨论】:

      猜你喜欢
      • 2021-11-05
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多