Я думаю, что мне не хватает того, как работают функции before и beforeEach в Cypress. У меня есть файл спецификации, который загружает данные из прибора в методе before. Некоторые из этих данных используются в функции before, а затем снова в функции beforeEach, а также в реальных тестах. Спецификационный файл содержит 2 теста. Первый тест выполняется, как и ожидалось. Второй сбой, потому что beforeEach говорит, что одно из значений из прибора не определено.
Я ожидаю, что если я загружу данные из прибора в методе before, он будет доступен для всех тестов в файле спецификации.
При выполнении проверки состояния панели кнопок тест window.console.log (this.user_data) в функции beforeEach выводит user_data, как и ожидалось.
При выполнении теста «Отправить форму» окно window.console.log (this.user_data) в функции beforeEach выводит undefined и тест останавливается.
Что мне здесь не хватает?
describe('Customer Profile', () => {
before(function () {
window.console.log('Enter the before function')
// Load the fixture data. Its asynchronous so if we want to use it right here and now
// we have to put the things that use inside a callback to be executed after the data
// loaded.
cy.fixture('user').as('user_data').then(function (){
window.console.log('Fixture has loaded the user data')
cy.visit('/LaunchPad/login')
// Fill out the login form
cy.get('input[name="username"]').type(this.user_data.username)
cy.get('input[name="password"]').type(this.user_data.password)
cy.get('button[type="submit"]').click()
})
})
beforeEach(function(){
window.console.log('Enter the beforeEach function')
window.console.log(this.user_data)
// Preserve the cookies for all tests in this suite
Cypress.Cookies.preserveOnce('SESSION')
// Open the profile view
cy.visit('/Manager/'+this.user_data.org+'/config/company-profile')
})
it('Check the state of the button bar', function(){
window.console.log('Running test of button bar')
cy.get('section.content-header > h1').contains('Company Profile Details')
// Check the state of the action bar and its buttons
cy.get('section.action-bar').get('label.btn.btn-sm.btn-primary').contains('Save')
.should('have.attr', 'for', 'submit-form')
.should('have.attr', 'tabindex', '0')
cy.get('section.action-bar').get('#resetButton').contains('Reset')
.should('have.attr', 'type', 'reset')
.should('have.attr', 'value', 'Reset')
.should('have.class', 'btn btn-sm btn-default')
cy.get('section.action-bar').get('a.btn.btn-sm.btn-default').contains('Cancel')
.should('have.attr', 'href', '/Manager/'+this.user_data.org+'/')
cy.get('section.action-bar').get('a').contains('Delete').should('not.exist')
})
// This form has no required fields and no validation. So just pick a value or two
// submit the form and verify the banner is correct
it('Submit form', function(){
window.console.log('Running the submit form test')
cy.fixture('company_profile').as('company_profile')
cy.get('#companyProfileDto.name').type(this.company_profile.name)
})
})
UPDATE
После прочтения, основываясь на том, что ответил Карлос Альфредо, я пришел к этому.
1. Мне все еще нужно посетить страницу входа. Мы используем csrf и OATH, и попытка получить рабочий пример просто занимает слишком много времени.
2. Я должен использовать белый список для куки-файла сессии, потому что preserveOnce не работает вообще.
Вот файлы, которые у меня есть сейчас. Он посещает страницу входа один раз и получает настройку сеансовых файлов cookie. Два теста проходят, как и ожидалось.
поддержка / index.js
before(function(){
cy.login('bob', 'password')
cy.fixture('user').as('user_data')
cy.fixture('company_profile').as('company_profile')
})
beforeEach(function(){
window.console.log('Enter the global beforeEach function')
// Load the fixture data
})
поддержка / commands.js
/*
We visit the login form despite what the best practise recommendation is because
we have OAUTH redirects and a CSRF token to deal with. Since the majority of the
examples and working use cases provided dont deal with those scenarios this is
the best I can do at the moment.
*/
Cypress.Commands.add('login', (username, password, options = {}) => {
cy.visit('/LaunchPad/login')
// Fill out the login form
cy.get('input[name="username"]').type(username)
cy.get('input[name="password"]').type(password)
cy.get('button[type="submit"]').click()
})
/*
We are white listing the cookie because Cypress.Cookies.preserveOnce('SESSION')
does not work. https://github.com/cypress-io/cypress/issues/2952
Because we are forcing Cypress to not clear the cookies, you will have to close
the test window after the suite is completed other wise the Vision360 apps will
think your session is alive.
*/
Cypress.Cookies.defaults({
whitelist: 'SESSION'
})
интеграция / customer_profile / customer_profile_spec.js
describe('Customer Profile', () => {
it('Check the state of the button bar', function(){
window.console.log('Running test of button bar')
cy.visit('/Manager/'+this.user_data.org+'/config/company-profile')
cy.get('section.content-header > h1').contains('Company Profile Details')
// Check the state of the action bar and its buttons
cy.get('section.action-bar').get('label.btn.btn-sm.btn-primary').contains('Save')
.should('have.attr', 'for', 'submit-form')
.should('have.attr', 'tabindex', '0')
cy.get('section.action-bar').get('#resetButton').contains('Reset')
.should('have.attr', 'type', 'reset')
.should('have.attr', 'value', 'Reset')
.should('have.class', 'btn btn-sm btn-default')
cy.get('section.action-bar').get('a.btn.btn-sm.btn-default').contains('Cancel')
.should('have.attr', 'href', '/Manager/'+this.user_data.org+'/')
cy.get('section.action-bar').get('a').contains('Delete').should('not.exist')
})
// This form has no required fields and no validation. So just pick a value or two
// submit the form and verify the banner is correct
it('Submit form', function(){
window.console.log('Running the submit form test')
cy.visit('/Manager/'+this.user_data.org+'/config/company-profile')
// Fill and submit the form
cy.get('input#companyProfileDto\\.name').clear().type(this.company_profile.name)
cy.get('section.action-bar').get('label.btn.btn-sm.btn-primary').contains('Save').click()
// Check the response
cy.get('.callout-success').contains('Your changes are saved.')
cy.get('input#companyProfileDto\\.name').should('have.value', this.company_profile.name)
})
})