Alex
Alex

Reputation: 465

How would I get the value from the hidden input using Cypress?

I need to save the token which is stored in this hidden input.

This is my request:

cy.request({
  method: 'GET',
  url: '/auth/login',
  body: {
    email: email,
    password: password,
  },
}).then((response) => {
    const page = response.body;
});

The response.body returns:

<!DOCTYPE html>
<html>
    <body>
        <form class="form" action="" method="post" autocomplete="off">
            <input id="email" class="form-control" type="text" name="email" placeholder="Email" />
            <input id="password" class="form-control" type="password" name="password" placeholder="Password" />
            <input type="hidden" name="_token" value="c5LWQtrMVkKXxBFKs1zFzrJYq4PgNifndvcV0F6O">
            <button type="submit">Login</button>
            <a href="https://testing.com">Other Login</a>
        </form>
    </body>
</html>

I'm not sure how I find/grab the value from the hidden input with the name _token

Upvotes: 2

Views: 2564

Answers (1)

Mischa
Mischa

Reputation: 733

From the cypress CSRF example:

  it('strategy #1: parse token from HTML', function () {

    // to fetch the login page, and then parse the HTML contents
    // to find the CSRF token embedded in the page
    cy.request('/auth/login')
    .its('body')
    .then((body) => {
      // we can use Cypress.$ to parse the string body
      // thus enabling us to query into it easily
      const $html = Cypress.$(body)
      const token = $html.find('input[name=_token]').val()

      ...[see link for full code]
    })

Note: above example is for cypress v4. For latest cypress version, see here.

Upvotes: 2

Related Questions