9

I notice that X-CSRFToken header is getting removed between tests, for all the XHR requests that triggered from application under test. I'm not sure to preserve this header, as I'm already preserving the Cookies through Cypress.Cookies.preserveOnce('sessionid', 'csrftoken')

Hence, I thought of appending the custom header X-CSRFToken to all the XHR requests from the application. Here is the script I used, where I'm fetching the csrftoken from cookies and setting to custom header.

cy.server({
   onAnyRequest: function(route, proxy) {
        proxy.xhr.setRequestHeader('X-CSRFToken', cy.getCookie('csrftoken'));
   }
})

Here, I'm getting the below error,

Argument of type '{ onAnyRequest: (route: any, proxy: any) => void; }' is not assignable to parameter of type 'Partial<ServerOptions>'.
  Object literal may only specify known properties, and 'onAnyRequest' does not exist in type 'Partial<ServerOptions>'.

I'm expecting any working solution to this approach or a better solution.

Kondasamy Jayaraman
  • 1,802
  • 1
  • 20
  • 25

4 Answers4

9

Now cy.server is deprecated, you can use cy.intercept instead:

cy.intercept('http://api.company.com/', (req) => {
  req.headers['authorization'] = `token ${token}`
})

More info in the docs.

Yair Cohen
  • 2,032
  • 7
  • 13
  • 1
    works perfect, thank you! Optionally, you can set e.g. `'GET'` or `'POST'` as the first parameter. –  Dec 25 '21 at 17:23
5

Just to make everyone aware, I communicated with makers of Cypress and got to know that the stubbing of outgoing request is under development and can be tracked under - https://github.com/cypress-io/cypress/issues/687

Kondasamy Jayaraman
  • 1,802
  • 1
  • 20
  • 25
4

Run your code in a beforeEach statement.

beforeEach(() => {
    cy.server({
        onAnyRequest: function(route, proxy) {
           proxy.xhr.setRequestHeader('X-CSRFToken', cy.getCookie('csrftoken'));
       }
    })
});
Randy
  • 1,498
  • 13
  • 8
0

I think you're looking for onRequest instead of onAnyRequest. Here's the documentation for cy.server options

kuceb
  • 16,573
  • 7
  • 42
  • 56