在赛普拉斯中使用别名 [英] Using aliases in Cypress
问题描述
我正在尝试使用别名在 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屋!