Kenneth Truong
Kenneth Truong

Reputation: 4166

How do I log a specific field in API requests within Cypress

I want to cypress.log() out a specific field in the request header whenever my webapp makes requests that way when it fails and adds screenshots/logs I can grab that that requestId that failed.

Is there a way to setup cypress so that for all network requests it checks for this field and log it?

I can add a cy.intercept within each individual file but I want a more generic way to handle this.

enter image description here

Upvotes: 3

Views: 774

Answers (2)

Fody
Fody

Reputation: 31954

Cypress.log is the synchronous version of cy.log().

Add middleware: true to the intercept to pass request to other intercepts.

cy.intercept({ url: '*', middleware: true }, (req) => {

  const headerValue = req.headers?['x-custom-headers']  

  if (headerValue) {
    Cypress.log({
      name: 'x-custom-header',
      message: headerValue
    })
  }
})

Upvotes: 4

jjhelguero
jjhelguero

Reputation: 2555

You'll get an Cypress promise error if you try to use cy.log() to log out every request header in an cy.intercept() within a routeHandler callback. This would also make it kind of tough to log to a CI terminal as well.

Instead you can console.log to dev tools. To make it apply to all tests, you can wrap it in a beforeEach() and place it in the support/index.js file.

// support/index.js

beforeEach(() => {
  cy.intercept('*', (req) => {
      req.continue((res) => {
        console.log(JSON.stringify(req.headers))
      })
    })
})

Upvotes: 1

Related Questions