在赛普拉斯中使用别名

Rut*_*uth 5 cypress

我正在尝试使用别名在我beforebeforeEach钩子之间共享值。如果我的值是字符串,则当前有效,但是当值是对象时,别名仅在第一个测试中定义,此后的每个测试this.user在我的beforeEach挂钩中均未定义。如何在测试之间共享作为对象的值?

这是我的代码:

before(function() {
  const email = `test+${uuidv4()}@example.com`;
  cy
    .register(email)
    .its("body.data.user")
    .as("user");
});

beforeEach(function() {
  console.log("this.user", this.user); // This is undefined in every test except the first
});
Run Code Online (Sandbox Code Playgroud)

Ric*_*sen 5

别名变量通过cy.get('@user')expect(user)语法访问。我了解这是因为某些命令本来就是异步的,因此使用包装器访问变量可确保在使用变量之前对其进行解析。

请参阅文档变量和别名获取

如果要访问全局user值,可以尝试类似的方法

let user;

before(function() {
  const email = `test+${uuidv4()}@example.com`;
  cy
    .register(email)
    .its("body.data.user")
    .then(result => user = result);
});

beforeEach(function() {
  console.log("global user", user); 
});
Run Code Online (Sandbox Code Playgroud)

那里的then解决方案像一个诺言,但您应谨慎对待解决问题的延迟- console.log可能在之前运行then

  • @itcropper,问题仍然存在。这些文档没有涵盖在“before()”而不是“beforeEach()”中创建别名的场景,因此这是有效的用法。 (3认同)
  • 谢谢!最后我选择了 `cy.get('@user')`。但是,[文档](https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Sharing-Context) 暗示 `this.user` 语法应该以这样的方式工作我试过。 (2认同)