我正在尝试使用commands.ts来简化重复操作,例如询问电子邮件和密码。
但是当我尝试使用它时,它给了我登录错误(“登录”类型的参数不可分配给“keyof Chainable”类型的参数)
`
Cypress.Commands.add("login", (email, password) => {
some codes....
})
`
我没有尝试过任何其他事情
新答案
使用
创建文件
global.d.ts
namespace Cypress {
interface Chainable {
login(email:string, password:string): Chainable<void>;
}
}
旧答案
创建与commands.ts同一级别的文件index.ts
放入里面
export {}
declare global {
namespace Cypress {
interface Chainable {
login(email:string, password:string): Chainable<void>;
}
}
}
享受
更新 - 为什么它有效
当我们使用 Typescript 时,一切都需要一个接口来描述。 在您的示例中,Cypress 有其 Chainable 接口,但您希望它也有“登录”属性。 使用此代码,您是说您想要扩展“Cypress.Chainable”以拥有登录属性。
我再用一个真实的例子来给大家解释一下
interface String {
myOwnChainableFunction: Function
}
String.prototype.myOwnChainableFunction = function (this: string){
console.log(this)
}
'ciao'.myOwnChainableFunction();
在这个例子中,我们正在扩展 String 原型以接受我们自己的链式函数。 在 Javascript 中,我们只需将其附加到原型,但使用 .ts,Typescript 检查器会假装此属性存在于 String 接口中,因此我们也将其添加到接口中。