gpt4 book ai didi

javascript - 如何将数据类型附加到 Cypress.as 别名函数

转载 作者:行者123 更新时间:2023-12-05 02:34:02 25 4
gpt4 key购买 nike

我有一个对象,我从中创建了一个名为 userId 的别名

cy.wrap(response.id).as('userId');

当引用 userId 时,它的类型是 JQuery<HTMLElement>

cy.get('@userId').then(userId => // userId type is JQuery<HTMLElement> });

定义别名时如何定义别名类型

目的是将其作为 number直接代替默认 JQuery<HTMLElement>

编辑

我不想要这样的东西

cy.get<number>('@userId').then(userId => // userId type is number });

我想在函数定义时定义类型。

最佳答案

问题出在 cypress.d.ts 中的这两个类型定义中

// cypress.d.ts

/**
* Get one or more DOM elements by selector.
* The querying behavior of this command matches exactly how $(…) works in jQuery.
* @see https://on.cypress.io/get
* @example
* cy.get('.list>li') // Yield the <li>'s in <.list>
* cy.get('ul li:first').should('have.class', 'active')
* cy.get('.dropdown-menu').click()
*/
get<E extends Node = HTMLElement>(
selector: string,
options?: Partial<Loggable & Timeoutable & Withinable & Shadow>)
: Chainable<JQuery<E>>

/**
* 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>

您可以通过颠倒顺序来“修复”它,

// cypress/support/index.ts

declare global {
namespace Cypress {
interface Chainable<Subject> {
// change the order of these two dfns
get<S = any>(alias: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<S>
get<E extends Node = HTMLElement>(selector: string, options?: Partial<Loggable & Timeoutable & Withinable & Shadow>): Chainable<JQuery<E>>
}
}
}

现在cy.get('@alias')类型为 any (因为 get<S = any> ),这是有效的,因为别名存储任何类型。

还有selector版本被输入到 any同样,相同的类型签名似乎使其中一个 defns 变得多余。

正如 Mikhail Bolotov 指出的那样,使用不同的命令名称可以解决问题,但我会在 /cypress/support/index.ts 中将其定义为自定义命令。并称之为getAlias因为它必须适用于任何类型。

关于javascript - 如何将数据类型附加到 Cypress.as 别名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70825942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com