Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Cypress preserving cookies over for a complete test suite

I am testing that requires you to be logged in while performing tests. In order to stay logged in I am preserving Cookies during a test run.

I use a custom function:

Cypress.Commands.add('preserveAllCookiesOnce', () => {
    Cypress.Cookies.defaults({
        preserve: (cookie) => {
            return true;
        }
    })
})

Also tried

beforeEach(function () {
        Cypress.Cookies.preserveOnce('session', 'YII_CSRF_TOKEN');
    })

(Double-checked the name of the cookies)

Now in this test case I have included two post requests after logging in. But after those two POST request tests I get a 403 error when trying to access the page again.

If you need more details, please let me know. I am trying to keep the code to the minimum needed to understand the problem:

import {Login} from "../../pages/login/Login";

describe('test POST/client validation', () => {
    beforeEach(function () {
        cy.preserveAllCookiesOnce()
    })
    it('log in', () => {
        login.goToLoginPage()
        login.loginCredentials(Cypress.env('userEmail'), Cypress.env('userPass'))
    })
    it('test some stuff', function () {
        cy.visit(Cypress.env('url') + '/index.php?r=tc/tcSettings/index&language=de')
        .....
    })
    it('send POST/client request with incorrect values', function () {
        cy.request({
            method: 'POST',
           ...
        })
            .then(response => {
                expect(response.status).to.eq(400)
                expect(response.body.fields).to.contain({stuff})
            })
    })
    it('send POST/client request with correct values', function () {
            cy.request({
              ...
            })
                .then(response => {
                    expect(response.status).to.eq(200)
                })
    })
    it('go to clients page and assert created client', () => {
            cy.visit(Cypress.env('url') + '/index.php?r=client/index&language=de') 
    })
})

It looks like preserving the cookies does not work through the POST tests. When I try to access the website in the last step I get a 403 status.

Usually I can run any number of it instances with the command cy.preserveAllCookiesOnce() so my guess it, that it might have to do with the POST requests in between

Screenshot of Cookies after the POST step:

Cookies console

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Is the cy.preserveAllCookiesOnce() a custom command that you created in your Cypress's project? Note that you should use Cypress.Cookies.preserveOnce() instead:

beforeEach(function () {
    // before each test, we can automatically preserve the
    // 'session_id' and 'remember_token' cookies. this means they
    // will not be cleared before the NEXT test starts.
    //
    // the name of your cookies will likely be different
    // this is an example
    Cypress.Cookies.preserveOnce('session_id', 'remember_token');
})

To enable or disable cookie debugging, use Cypress.Cookies.debug().

// Cypress will now log in the console when
// cookies are set or removed
Cypress.Cookies.debug(true)

cy.setCookie('fakeCookie', '123ABC')
cy.clearCookie('fakeCookie')
cy.setCookie('fakeCookie', '123ABC')
cy.clearCookie('fakeCookie')
cy.setCookie('fakeCookie', '123ABC')

You can read more about Cypress.Cookies's API here.

about 4 years ago · Juan Pablo Isaza Relatório

0

Ok, I have finally found the cause of the problem. It does have to do with Cookies, but I absolutely can't explain what causes it.

In the first step I login as an Admin user. I save the session cookies for this user and then proceed to do the POST requests.

Yet, in step 5 when I want to check the clients page, I am suddenly logged in as a non-Admin user (a 2nd test account that I have created to make tests with non-Admin permissions).

To summarize:

it('log in', () => {
        //in this step I log in as Admin
    })
    it('test some stuff', function () {
        //in this step I am still logged in as Admin
    })
    it('send POST/client request with incorrect values', function () {
        //still logged in as Admin
    })
    it('send POST/client request with correct values', function () {
        //suddenly log in changes to non-Admin account
    })
    it('go to clients page and assert created client', () => {
        //logged in as non-Admin, therefor this test fails
    })
})

I can not find any reason in my code why the log-in state changes in the POST test.

But even though I can not find the reason, I can now work around the problem by adding an extra step before step 5 that just logs out and back in as Admin user.

This is the code for the POST step that causes the login to change:

it('send POST/client request with incorrect values', function () {
        cy.request({
            method: 'POST',
            url: Cypress.env('url') + '/service/clients',
            headers: {
                'API-KEY': api_key,
            },
            body: body1,
            failOnStatusCode: false
        })
            .then(response => {
                expect(response.status).to.eq(400)
                expect(response.body.fields).to.contain({
                    "some stuff"
                })
            })
    })

I see no reason why this request should change the state of my session tbh. Plus the login credentials for the non-Admin user are used nowhere inside this spec file

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda