How to programmatically login in Cypress for PHP larvavel session website

781 views Asked by At

I writing testing code in Cypress. UI login has been tested with no problem, but in order to test other parts of the website, I'd like to programmatically log in for quick testing. The website is written in PHP and uses laravel session in the set-cookie of headers and here below is my code:

spec.ts

it('strategy #2: parse token from response headers', function () {
        // if we embed our csrf-token in response headers
        // it makes it much easier for us to pluck it out
        // without having to dig into the resulting HTML
        cy.request('/auth/login')
        .its('headers')
        .then((headers) => {
          const laravel_session = headers['laravel_session']
    
          cy.loginByCSRF(laravel_session)
          .then((resp: any) => {
            expect(resp.status).to.eq(200)
            expect(resp.body).to.include('<span class="menu-item">Dashboard</span>')
          })
        })
    
        // Set viewport to 1366px x 1024px
        cy.viewport(1366, 1024)

command.ts

Cypress.Commands.add('loginByCSRF', (laravel_session: string) => {

    const username = environment.Admin_username
    const password = environment.Admin_password

    cy.request({
        method: 'POST',
        url: '/auth/login',
        failOnStatusCode: false, // dont fail so we can make assertions
        form: true, // we are submitting a regular form body
        body: {
          username,
          password,
          _laravel_session: laravel_session, // insert this as part of form body
        },
    })
})

index.d.ts

declare namespace Cypress {
    interface Chainable {

        loginByCSRF: typeof loginByCSRF
    }
}

function loginByCSRF(laravel_session) {
    return this.headers
}

Any help is appreciated. Thanks!

1

There are 1 answers

0
Bas von Bassadin On

Not sure if you found an answer already, but the laracasts cypress package has this function and some other really neat things :)