DEV Community

Samsul Islam
Samsul Islam

Posted on • Edited on

Cypress automation login with csrftoken

Here in this article, I am going to show you how to extract csrftoken from html body and use it in login form as payload.
I assume you have installed https://nodejs.org/en/ and create a cypress project https://www.cypress.io/.
Open cypress project with this command.

npx cypress open

It will open a cypress window then click E2E Testing button. After that click on the Start E2E Testing with you browser and create New empty spec file with a name like loginWithCsrfToken.cy.js
Add the below code in your loginWithCsrfToken.cy.js file.

Image description
Let's short brief about my code, here describe is collection of it blocks.

Image description

Here i wrote a custom command, you can write it in support folder. custom command takes a name and a parameter like csrfToken

Cypress.env read the item from the cypress.config.js file where i have set env variable as object. like env: {
baseUrl : "http://quotes.toscrape.com",
username: "ranafge",
password: "pass1478"
}

cy.request allow us to parse html and send http request.

Now let's go to the second part the it block
it('Parse from csrf token from HTML', function() {
cy.request('http://quotes.toscrape.com/login')
.its("body")
.then((body)=>{
const $html = Cypress.$(body)
const csrfToken = $html.find('form > input[type=hidden]:nth-child(1)').val();
console.log(csrfToken)
cy.loginWithCsrfToken(csrfToken) .then((res)=>{
expect(res.status).to.eql(200)
expect(res.body).to.include('Logout')
cy.visit(Cypress.env('baseUrl'))
})
})
})
`
Here .its Get a property's value on the previously yielded subject as per documentation.

Cypress.$ is a jQuery function tha take a selector. After parsing the csrf token then just call the custom command with the name _cy.loginWithCsrfToken(csrfToken) _ and pass a parameter csrfToken that extracted.

This was the first article, I appoloze for my any mistake.

Top comments (0)