在赛普拉斯中使用别名 [英] Using aliases in Cypress

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

问题描述

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

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.

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

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

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

其中,然后像诺言般解决,但是您应该谨慎对待解决问题的延迟- console.log 可能先于然后运行。

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

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

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