使用"this"访问赛普拉斯中的别名. [英] Accessing aliases in Cypress with "this"

查看:66
本文介绍了使用"this"访问赛普拉斯中的别名.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to share values between my before and beforeEach hooks using aliases. It currently works if my value is a string but when the value is an object, the alias is only defined in the first test, every test after that this.user is undefined in my beforeEach hook. How can I share a value which is an object between tests?

这是我的代码:

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
});

推荐答案

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

Aliased variables are accessed via cy.get('@user') or expect(user) syntax. I understand this is because some commands are inherently asynchronous, so using a wrapper to access the variable ensures it is resolved before being used.

请参见文档变量和别名获取.

如果您要访问全局 user 值,则可以尝试类似

If you want to access a global user value, you might try something like

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); 
});

then 的解析就像一个承诺,但是您应谨慎对待解决问题的延迟- console.log 可能先于 then .

where the then resolves like a promise, but you should be wary of delay in resolving - the console.log may run before the then.

这篇关于使用"this"访问赛普拉斯中的别名.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆