您应该阅读文档中处理 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 访问它。
- 使用这种方法,您可以轻松存储 10 个或更多文本元素,然后在平面层次结构中访问它们
- 但请注意
function () 语法。您不能使用 phat 箭头语法,因为您的 this 上下文是错误的
- 您还可以利用
should 命令的重复功能。它将重试您的回调,直到没有断言失败或达到超时为止
- 这也适用于 Typescript。当然,Typescript 不知道属性
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>;
}
}
}
https://github.com/cypress-io/cypress/issues/4022 合并后可以删除。