我正在将现有的自定义命令转换为打字稿,但遇到了障碍。我的自定义命令返回了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'.
答案 0 :(得分:0)
我发现了一个我现在正在使用的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);