https://cypress.io logo
How to override cy.request() and set up bearer aut...
# i-need-help
b
I need to set the authorization bearer header for
cy.request()
globally to avoid setting it up multiple times. Here https://lightrun.com/answers/cypress-io-cypress-default-headers-for-cyrequest-command#:~:text=As%20a%20workaround%20I%20overwrite%20cy.request%20method%20with%20my%20custom%20command%3A I found some potential way to do it. So in my
support/commands.ts
I have:
Copy code
Cypress.Commands.overwrite('request', (originalFn, ...options) => {
    const optionsObject = options[0];
    if (optionsObject === Object(optionsObject)) {
      optionsObject.headers = {
        authorization: `Bearer ${Cypress.env('authorizationToken')}`,
        ...optionsObject.headers,
      };
      return originalFn(optionsObject);
    }
    return originalFn(...options);
});
And in the test I have:
Copy code
cy.request({
    method: 'POST',
    url: '/someEndpoint',
    body: someBody
}).then(response => {
    expect(response.status).eq(200);
    return response.body;
});
And unfortunately, I get 401: Unauthorized error and it looks like the authorization bearer token was not added to headers: What do I do wrong here? I use Cypress v 10.10.0
n
do you import this command in your test file?
import '../../commands/request'
b
why?
request
is part of the Cypress global namespace so I don't need to import it anywhere. It is accessible anywhere using
cy.
Even if I import it it shows as not used:
s
one question
did you set a bearer token in your command
?
g
you can use
debugger
keyword in your overwrite and open Devtools to confirm your header is set and the token is correct
p
write a new command that uses request command that adds header: property to the request body ?
b
yes I did in this line of code:
Copy code
authorization: `Bearer ${Cypress.env('authorizationToken')}`,
I get it from environment variables. I also tried to paste a full token as a string and still it wasn't added to headers.
g
In my bonus lesson 76 in https://cypress.tips/courses/network-testing I have this situation (common custom request header, both on intercepts and on overwritten cy.request), unfortunately it is a paid course
e
What are the two returns for? Shouldn't this only need
return originalFn(optionsObject);
at the end there?
w
You could also set up an intercept that appends the header.
Copy code
cy.intercept(`<pattern to match>`, (req) => {
    req.headers["<header>"] =
      "<token>";
  });