While running the Cypress test, receiving The response we received from your web server was: > 401: Unauthorized and cypress displays Authorization": "Bearer undefined" in the error details.
While debugging, the beforeEach > loginToPortal() method is returning valid token successfully. Not sure why the token is not passing to the deleteTestCompanies method. It would be of great help if someone could shed some light on this issue ?
Following is the error received
The request we sent was:
Method: GET
URL: https://somesite.com/api/Companies
Headers: {
"Connection": "keep-alive",
"Authorization": "Bearer undefined",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
"accept": "*/*",
"accept-encoding": "gzip, deflate"
}
beforeEach(
"Login to web Portal and Navigate to some Page",
function() {
cy.server();
cy.loginToPortal().then((response) => {
cy.deleteTestCompanies(this.bearerToken);
cy.setTokens({ token: this.bearerToken });
});
cy.visit("/stateprofile");
}
);
support/index.js
import "./commands";
import "./apiCommands";
// Below functions are in "apiCommands.js " file;
Cypress.Commands.add("getCompanies", token => {
cy.request({
url: "/api/Companies",
headers: {
Authorization: `Bearer ${token}`
}
}).then(response => {
var matchedCompany = [];
const companies = response.body;
companies.forEach(function(element, index) {
if (companies[index].name.includes("test-")) {
matchedCompany.push(companies[index].id);
}
});
cy.wrap(matchedCompany).as("testCompanies");
});
});
Cypress.Commands.add("deleteTestCompanies", token => {
cy.getCompanies().then(companies => {
companies.forEach(function(element, index) {
cy.request({
method: "DELETE",
url: `/api/companies/${companies[index]}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-type": "application/json"
}
});
});
});
});
I have passed the token inside the cy.getCompanies(token) method and resolved the problem. Also console.log("InsideCompanies:" +token) the token inside the loop.
Cypress.Commands.add("deleteTestCompanies", token => {
cy.getCompanies(token).then(companies => {
companies.forEach(function(element, index) {
console.log("InsideCompanies:" +token);
cy.request({
method: "DELETE",
url: `/api/companies/${companies[index]}`,
headers: {
Authorization: `Bearer ${token}`,
"Content-type": "application/json"
}
});
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With