Search code examples
javascripttestingautomationautomated-testscypress

Error when setting Header in all requests - Cypress (JS)


I have the following question. Could you help me?

I want to set custom header in all requests in my automated tests: "Content-Type" and "accept".

How can i get?

I tried that way but without success...

File commands.js

Cypress.Commands.add(
  'makeRequest',
  ({ headers }) => {
    cy.request({
      headers: {
        'Content-Type': 'application/json',
        'accept': 'application/json'
      }
  }

File index.js

beforeEach(() => {
  cy.makeRequest();
  });

Error below:

TypeError: Cannot destructure property 'headers' of 'undefined' as it is undefined. Because this error occurred during a before each hook we are skipping all of the remaining tests.

If anyone can help, it will be appreciated!!! If there is any other way to do what I want, let me know too!! thanks in advance

> After adjusting according to suggestion...

commands.js file

    Cypress.Commands.add(
  'makeRequest',
  (headers = {}) => {
    headers = {
      'Content-Type': 'application/json',
      'accept': 'applicationdsd/json',
      ...headers
    }
    cy.request({
      headers
    })
  }
)

index.js file

beforeEach(() => {
cy.makeRequest({'accept': 'text/html'}); 

Solution

  • You can probably see from the error message that passing nothing here cy.makeRequest() gives a problem here ({ headers }) => {, since you are not passing anything in.

    You can get rid of the brackets, for example this will not error

    Cypress.Commands.add(
      'makeRequest',
      (headers) => {
        cy.request({
          headers: {
            'Content-Type': 'application/json',
            'accept': 'application/json'
          }
        })
      }
    })
    
    cy.makeRequest();
    

    but you aren't using the headers parameter.


    If you want to add extra headers or perform one-time over-ride, you need this

    Cypress.Commands.add(
      'makeRequest',
      (url, headers = {}) => {           
        
        headers = {
          'Content-Type': 'application/json',
          'accept': 'application/json',
          ...headers                // add or over-ride headers from parameter
        }
    
        cy.request({
          url, 
          headers
        })
      }
    })
    
    cy.makeRequest(myUrl, {'accept': 'text/html'});  // change this header one time only