别名在每个测试中未定义,除了第一个,因为别名在每次测试之后被清除。
别名变量通过cy.get('@user') 语法访问。某些命令本质上是异步的,因此使用包装器访问变量可确保在使用之前对其进行解析。
请参阅文档 Variables and Aliases 和 get。
似乎没有办法显式保留别名,就像 cookies 一样
Cypress.Cookies.preserveOnce(names...)
但是这个recipe for preserving fixtures 显示了一种通过在beforeEach() 中恢复全局变量来保留全局变量的方法
let city
let country
before(() => {
// load fixtures just once, need to store in
// closure variables because Mocha context is cleared
// before each test
cy.fixture('city').then((c) => {
city = c
})
cy.fixture('country').then((c) => {
country = c
})
})
beforeEach(() => {
// we can put data back into the empty Mocha context before each test
// by the time this callback executes, "before" hook has finished
cy.wrap(city).as('city')
cy.wrap(country).as('country')
})
如果您想访问全局 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);
cy.wrap(user).as('user'); // set as alias
});
it('first', () => {
cy.get('@user').then(val => {
console.log('first', val) // user alias is valid
})
})
it('second', () => {
cy.get('@user').then(val => {
console.log('second', val) // user alias is valid
})
})