首页 > 解决方案 > 赛普拉斯抛出未定义的授权承载,并且未传递令牌

问题描述

运行 Cypress 测试时,接收The response we received from your web server was: > 401: Unauthorized和 cypress 显示Authorization": "Bearer undefined"在错误详细信息中。调试时, beforeEach > loginToPortal() 方法成功返回有效令牌。不确定为什么令牌没有传递给deleteTestCompanies方法。如果有人能对这个问题有所了解,那会很有帮助吗?

以下是收到的错误

我们发送的请求是:

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";

// 下面的函数在“apiCommands.js”文件中;

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"
        }
      });
    });
  });
});

标签: javascriptcypress

解决方案


我已经通过了token里面的cy.getCompanies(token)方法并解决了问题。也是console.log("InsideCompanies:" +token)循环内的令牌。

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"
        }
      });
    });
  });
});

推荐阅读