We have written cypresstests that we now want to divide into code blocks. Before starting do divide code all tests ran accordingly and passed. But since changing into blocks we started to get errors about 401 authentication.
Is this the right syntax for code blocks in Cypress?
/* eslint-disable no-undef */
describe('Log in', () => {
it('Successfully loads', function () {
cy.visit('/')
.get('input[type="email"]')
.type('XXXX')
.get('input[type="password"]')
.type('XXXX')
.get('[style="text-align: center;"] > .ui').click()
})
describe('The Assignments Page', () => {
it('Add Assignment', function () {
cy.get('[href="/assignments"]').click()
cy.get('.grey').click()
cy.get('.ui > .search').type('Astra Zeneca')
cy.get(':nth-child(2) > .ui > input').type('System Development')
cy.get('textarea').type('This is a short text')
cy.get(':nth-child(4) > .ui').click()
cy.get('a.ui').click()
})
})
This makes total sense :) In the second test block "The Assignments Page" you're not logged in. You should log in using beforeEach
hook in every test block. In cypress, every test is executed on clean canvas to ensure that no errors from previous tests fail the next test. Means you HAVE TO login before every test. That's why you need beforeEach
hook.
Also the best practice here is to login programatically - means instead of clicking input field and typing (cy.type), send your login request with cy.request
and check if it's successful in the response.
Example code of login in beforeEach hook:
beforeEach(() => {
cy.request({
method: "POST",
url: '<YOUR LOGIN ENDPOINT>',
body: {
email: <VALUE>,
pass: <VALUE>
},
form: true
}).then(response => {
expect(response.status).to.eq(200);
expect(response.body.success).to.be.true;
});
};
}
your answer is really good help. Thank you! @DurkoMatko
@hereinsweden Great! If the answer helped you, you can accept it by clicking on big gray check button on the left side of the answer :) Welcome to Stack Overflow!