赛普拉斯(Cypress):如何在赛普拉斯中使用承载令牌写入GET请求?

时间:2020-05-03 04:52:27

标签: javascript networking get request cypress

我有两个请求:一个是POST请求,另一个是get。首先,我通过邮寄获取用户访问令牌,而在其他情况下,我使用此accessToken进行登录。我的代码不起作用。

我正在使用Window 7和Cypress 3.3.5

我的代码:

var value;
describe("Login operation", () => {
it("Login Request with post method", () => {
cy.request({
  method:'POST', 
  url:'https://odms.baitussalam.org:8445/api/v1/auth/login',
  body: {
    "userName": "faizanj",
    "password": "abc"
  }
})
      .then(function(response){
        this.value=response.body.accessToken;
        console.log("Value "+this.value);   
           expect(response.body.name).to.equal('Faizan');
          expect(response.status).to.equal(200);

      });

});

it('Second test case', function() {

var authHeader='bearer ${'+this.value+'}';
const options = {
  method: 'GET',
  url: `https://odms.baitussalam.org:8445/api/v1/qurbani-representative`,
  headers:{
    authorization:authHeader,
  }};

  cy.request(options)
  .then((response)=>{
expect(response.status).to.equal(200);6+9
});
});
});

1 个答案:

答案 0 :(得分:2)

问题在于,您尝试在测试用例之间使用变量集,当它已经重置为存储令牌时,您需要使用全局变量(不建议),或者创建一些登录命令,在您需要访问令牌之前调用该命令。例如:

Cypress.Commands.Add('login', (userName, password) => {
  cy.request({
      method:'POST', 
      url:'https://odms.baitussalam.org:8445/api/v1/auth/login',
      body: {
        userName,
        password,
      }
    })
    .as('loginResponse')
    .then((response) => {
      Cypress.env('token', response.body.accessToken); // either this or some global var but remember that this will only work in one test case
      return response;
    })
    .its('status')
    .should('eq', 200);
})

然后在使用 Cypress.env('token') 之前需要登录用户时。

例如:

describe('testing token', () => {
  beforeEach(() => {
    cy.login();
  });

  it('test request', () => {
    const token = Cypress.env('token');
    const authorization = `bearer ${ token }';
    const options = {
      method: 'GET',
      url: `https://odms.baitussalam.org:8445/api/v1/qurbani-representative`,
      headers: {
        authorization,
      }};

    cy.request(options)
      .its('status')
      .should('eq', 200);
  })
});

您可以更进一步并覆盖所有请求以向它们添加令牌,如下所示:

Cypress.Commands.overwrite('request', (originalFn, ...options) => {
  const optionsObject = options[0];
  const token = Cypress.env('token');

  if (!!token && optionsObject === Object(optionsObject)) {
    optionsObject.headers = {
      authorization: 'Bearer ' + token,
      ...optionsObject.headers,
    };

    return originalFn(optionsObject);
  }

  return originalFn(...options);
});

那么上面的例子应该是这样的:

describe('testing token', () => {
  beforeEach(() => {
    cy.login();
  });

  it('test request', () => {
    cy.request(options)
      .its('status')
      .should('eq', 200);
  })
});