Bruno Francisco
Bruno Francisco

Reputation: 4240

Set cookies and return user on Cypress request

Problem

I have a Cypress command where I can login with a random user. The API will return the following response:

{
  user: { ... }
  token: { ... }
}

What I would like to do is to:

  1. Create user using cy.request
  2. Set the cookie in the browser
  3. Return the response out of the command so that I can work with it outside of the command

What I have tried

return cy.request({
    method: 'POST',
    url: getApiUrl('__cypress__/login'),
    body: requestBody,
    log: false,
  })
    .then(({ body }) => {
      cy
        .setCookie('_token', body.token.plainTextToken)
        .then(() => {
          Cypress.log({
            name: 'login',
            message: JSON.stringify(body),
            consoleProps: () => ({ user: body }),
          });
        });
    })
    .its('body', { log: false }) 👈 times out here

What I'm looking for is to do something like:

cy.login().then(({ user }) => { 
  // use logged in user
})

Question

Cypress times out on .its(...) line. Is this possible to do it? Looking at the docs I couldn't find any example on what I'm trying to achieve

Upvotes: 2

Views: 1012

Answers (1)

Alex Izbas
Alex Izbas

Reputation: 625

(from the comments)

It happens because previously chained subject, does not return anything. An explicit return for the body property will fix it.

Upvotes: 3

Related Questions