best-lunch-5240
01/27/2023, 10:15 AMcy.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:
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:
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.0nutritious-honey-65632
01/27/2023, 10:47 AMimport '../../commands/request'best-lunch-5240
01/27/2023, 11:30 AMrequest 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:some-cartoon-73108
01/27/2023, 11:47 AMsome-cartoon-73108
01/27/2023, 11:47 AMsome-cartoon-73108
01/27/2023, 11:47 AMgray-kilobyte-89541
01/27/2023, 1:12 PMdebugger keyword in your overwrite and open Devtools to confirm your header is set and the token is correctpowerful-orange-86819
01/27/2023, 1:36 PMbest-lunch-5240
01/27/2023, 2:57 PMauthorization: `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.gray-kilobyte-89541
01/27/2023, 4:02 PMechoing-tent-95037
01/27/2023, 5:01 PMreturn originalFn(optionsObject); at the end there?witty-author-90805
01/27/2023, 8:01 PMwitty-author-90805
01/27/2023, 8:02 PMcy.intercept(`<pattern to match>`, (req) => {
req.headers["<header>"] =
"<token>";
});