2

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

D.Nykl
  • 147
  • 8
Kenneth Truong
  • 3,882
  • 3
  • 28
  • 47

2 Answers2

3

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
    })
  }
})
Fody
  • 23,754
  • 3
  • 20
  • 37
  • Thank you this helped! especially the part with the middleware and also showing how to use Cypress.log. I used a combination of this + the other answer with beforeEach. – Kenneth Truong Aug 22 '22 at 20:11
  • Actually, you don't need `beforeEach()`. Once you set up `cy.intercept()`, it is effective for all tests. – Fody Aug 22 '22 at 21:48
  • Where would you add this cy.intercept() code snippet? To the support/index.ts? – meightythree Aug 23 '22 at 20:56
  • I needed to add beforeEach because cy.intercept wasn't available without it. I added this to my support file. (also another note I ran into issues with using req.continue() so I removed that) – Kenneth Truong Aug 25 '22 at 17:14
  • 1
    Ok, but be aware that each call to `cy.intercept()` adds a new one to the stack - they don't overwrite or remove old versions. Perhaps `before()` is better? – Fody Aug 25 '22 at 19:41
  • 1
    WRT `req.continue()` you are correct, it looks like it negates the `middleware` flag and sends the request off to the server without allowing other intercepts to see the request. – Fody Aug 25 '22 at 21:00
1

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))
      })
    })
})
jjhelguero
  • 2,281
  • 5
  • 13