覆盖 cy.visit 时出现"赛普拉斯检测到您从命令返回了承诺,同时还调用了该承诺中的 cy 命令"错误



我正在尝试覆盖Cypress访问方法,以便在加载页面时关闭toast。这是一个草案,它只是试图得到元素的长度。

Cypress.Commands.overwrite('visit', (originalVisit, url, options = {}) => {
options.onLoad = () => {
const len = cy.get(BasePage.genericLocators.notificationToasts.releaseVersionToast).its.length;
console.log(len);
};
return originalVisit(url, options);
});

持续面临以下错误:

Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

返回承诺的命令是:

cy.visit()

您在promise中调用的cy命令是:

cy.get()

因为Cypress命令已经是类似promise的,所以您不需要包装它们或返回自己的promise。

Cypress将使用最终的Cypress命令生成的任何内容来解析您的命令。

这是一个错误,而不是警告,因为Cypress在内部串行排列命令,而Promises在调用命令后立即执行。试图调和这一点将阻止赛普拉斯解决问题。

不幸的是,您不能在像onload()这样的回调中使用Cypress排队命令(如cy.get()(,但可以使用Cypress.$()

Cypress.Commands.overwrite('visit', (originalVisit, url, options = {}) => {
options.onLoad = () => {
const toast = Cypress.$(BasePage.genericLocators.notificationToasts.releaseVersionToast);
console.log(toast.length);
};
return originalVisit(url, options);
});

尽管由于该元素是toast,您可能不会像那样捕获它,因为Cypress.$()上没有重试。


带重试的命令

或者,只需在测试中按顺序运行onload代码。

cy.visit('/')
cy.get(BasePage.genericLocators.notificationToasts.releaseVersionToast)
.should('be.visibile') 
.click()                  // close the toast

使用.should('be.visibile')对于捕获诸如toast消息之类的临时元素是必要的。


作为命令覆盖

您可以使用cy.wrap()在命令overwrite中执行上述操作,但如果您需要在cy.visit()之后使用窗口对象,则需要重新包装它。

Cypress.Commands.overwrite('visit', (originalVisit, url, options = {}) => {
return cy.wrap(originalVisit(url, options))
.then((win) => {

// click the toast away      
cy.get(BasePage.genericLocators.notificationToasts.releaseVersionToast)
.should('be.visibile') 
.click();
//re-wrap the win so that cy.visit() has same return value as before
cy.wrap(win)
})
})
cy.visit('/')
.then(win => {
// can use AUT window here as usual
})

注意标准cy.visit()已经在等待页面加载事件触发,因此不需要显式执行此操作。

相关内容

最新更新