DEV Community

Samsul Islam
Samsul Islam

Posted on • Updated 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 and create a cypress project
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
Add the below code in your 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 : "",
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() {
const $html = Cypress.$(body)
const csrfToken = $html.find('form > input[type=hidden]:nth-child(1)').val();
cy.loginWithCsrfToken(csrfToken) .then((res)=>{
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)

Visualizing Promises and Async/Await šŸ¤“

async await

ā˜ļø Check out this all-time classic DEV post on visualizing Promises and Async/Await šŸ¤“