我使用cypress
来测试我的注册和登录表单。我想在register.js
测试中设置cookie,然后在login.js
测试中使用它们。
我保存cookies在cypress/support/index.js:
Cypress.Cookies.defaults({
preserve: ['test_email', 'test_password'],
});
我的<<p> strong> register.js 测试看起来像这样:
describe('Create new account', () => {
it('Visit Register', () => {
cy.visit(Cypress.env('URL_REGISTER'));
cy.setCookie('test_email', 'fake@email.com');
cy.setCookie('test_password', 'abc123');
});
it('Fill out register form', async () => {
const email = await cy.getCookie('test_email');
const password = await cy.getCookie('test_password');
cy.get('[data-cy="register-email"]').type(email.value);
cy.get('[data-cy="register-password"]').type(password.value);
});
});
当我运行这个测试时,我得到这个错误:
无法读取未定义的属性'value'
我理解cy.getCookie()
返回一个对象并且是异步的,这就是为什么我试图使用await
,但出于某种原因,这似乎不起作用。如何在多个柏树测试中设置和获取cookie ?
使用Cypress.preserveOnce()在测试之间保存cookie,或在beforeEach()
中保存所有测试。
beforeEach(() => {
Cypress.Cookies.preserveOnce('test_email')
})
it('set cookie', async () => {
cy.setCookie('test_email', 'fake@email.com')
})
it('once', async () => {
const email = await cy.getCookie('test_email')
expect(email).to.have.property('value', 'fake@email.com') // passes
})
it('twice', async () => {
const email = await cy.getCookie('test_email')
expect(email).to.have.property('value', 'fake@email.com') // passes
})
it('thrice', async () => {
const email = await cy.getCookie('test_email')
expect(email).to.have.property('value', 'fake@email.com') // passes
})
你应该坚持使用文档中的getCookie方法。
如果我运行
const email = await cy.getCookie(...)
在cy.visit()
之后,我得到undefined
如果我使用
cy.getCookie(...).then(...)
在下一行,它得到值
由于Cypress没有在任何地方记录await语法,因此您可能会得到一些不稳定的结果。
标准格式为:
it('once', () => {
cy.getCookie('test_email').then(email => {
expect(email).to.have.property('value', 'fake@email.com') // passes
})
})
如果你在CI中运行测试,它们可能是并行运行的,所以最好在before()
或beforeEach()
中设置cookie。
before(() => {
cy.setCookie('test_email', 'fake@email.com')
})
beforeEach(() => {
Cypress.Cookies.preserveOnce('test_email')
})
it('uses cookie once', () => {
...
})
it('uses cookie twice', () => {
...
})
it('uses cookie thrice', () => {
...
})