除了第一个测试之外,别名在每个测试中都未定义,因为在每次测试后都清除了别名。
别名变量通过cy.get('@user')
语法访问。某些命令本质上是异步的,因此使用包装器访问变量可确保在使用之前对其进行解析。
请参阅文档变量和别名并获取.
似乎没有办法显式保留别名,就像cookie一样
Cypress.Cookies.preserveOnce(names...)
但是这个保存固定装置的方法显示了一种通过在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
})
})