![](/img/trans.png)
[英]Cypress Typescript: how to store a variable that can be used in the afterEach teardown?
[英]how to I store element text from cypress chain into a variable in typescript?
我想有一些测试用例来比较 tolPage 文本值与 curPage 文本值相同,如下所示。 但它不起作用,我应该如何将元素文本从柏树链传递到局部变量
class Menu{
tolPage() {
return cy
.get(selectors.pagination.totalPageCount)
.invoke('text')
.then((text) => {
return text.toString();
});
}
curPage() {
return cy
.get(selectors.pagination.currentPageCount)
.invoke('text')
.then((text) => {
return text.toString();
});
}
}
describe('check two function should be eq') {
const menu = new Menu();
it('Verified "', () => {
let text = menu.curPage();
# menu.tolPage().should('be.eq', text));
# menu.tolPage().should('be.eq', menu.curPage());
});
}
您应该阅读处理 cypress异步行为的文档部分: https : //docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Asynchronous
因此,您不能将menu.curPage()
分配给变量并期望该变量包含文本。
所以这会失败。 当到达expect
行时, testVar
仍然为空:
it("test", () =>{
let testVar = null;
cy.get("body").then(() => {
testVar = 5;
})
expect(testVar).to.eq(5)
})
相反,您可以这样编写(取决于您要测试的内容和方式):
it("test", () =>{
let testVar = null;
cy.get("body").then(() => {
testVar = 5;
})
cy.get("body").should(() => {
expect(testVar).to.eq(5)
})
})
因此,根据您的代码,您的解决方案可能类似于:
describe('check two function should be eq') {
const menu = new Menu();
it('Verified "', () => {
menu.curPage().then(cPText => {
menu.tolPage().then(tPText => {
expect(cPText).to.eq(tPText);
})
});
});
如果您必须检查两个以上的文本值,这种命令嵌套可能会很烦人。 为了让您的生活更轻松,您可以这样做:
describe("test", () => {
beforeEach(() => {
cy.visit("https://cypress.io")
})
it("test", () => {
getCaption();
getSubCaption();
// attention: function() syntax is required to keep `this` context
cy.get("body").should(function() {
expect(this.caption.indexOf("testing") > -1).to.eq(this.subcaption.indexOf("testing") > -1)
});
})
})
function getCaption() {
return cy.get(".Hero-TagLine.mt-0").invoke("text").as("caption");
}
function getSubCaption() {
return cy.get(".Hero-ByLine.mb-0").invoke("text").as("subcaption");
}
我添加了一个自己的示例,因此我能够为您提供一个可运行且有效的示例。 但是您可以轻松调整它以适合您的代码。 发生什么了:
cy.get().invoke("text").as("alias")
与在您的代码中的作用相同,只是它将文本内容存储在别名中。 Cypress 还为每个别名创建一个新的实例变量,因此您可以通过this.caption
访问它。
function ()
语法。 您不能使用 phat 箭头语法,因为您的this
上下文是错误的should
命令的重复功能。 它将重试您的回调,直到没有断言失败或达到超时this.caption
和this.subcaption
的属性。 因此,您必须在this
之前将其强制转换为any
或调整类型定义顺便说一句:我看到你做了这个: cy.get().invoke("text").then(t => t.toString())
以修复 TS 中的类型。 您可以通过使用自己的类型定义来避免这种情况:
declare global {
namespace Cypress {
interface Chainable {
invoke(fn: "text"): Cypress.Chainable<string>;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.