赛普拉斯发送多个请求,并且不允许登录

时间:2020-04-07 00:43:00

标签: javascript cypress

我正在使用Cypress 4.3.0版本,已经在cypress.json文件中设置了baseUrl =“ https://tenant-demo.somesitedev.net”。当我发送cy.request()命令时,它正在发送多个请求(请参见图1)。另外,当我观察到访问命令时,可以看到以下原始网址,已解析的网址和重定向。在这种情况下,如何使用cy.request()命令登录站点。

before(()=>{
    cy.visit('/').then(()=>{
        cy.get('input[type="hidden"]').invoke('val').then((val)=>{
                const token = val;
                cy.login(token);
        }) 
     })

    }) 

Cypress.Commands.add('login', (token) => {
    const username= 'test1.user';
    const password= 'somepassword';
    const accessToken = localStorage.getItem('tokens');
    const cookieValue = document.cookie.split(';');
    const configCat = localStorage.getItem('ConfigCat_');
  cy.request({
      method: 'GET',
      url: '/dashboard',
      failOnStatusCode: false,
      form: true,
      body:{
        _token: token,
        username,
        password
      },
      headers: {
        'accept': 'text/html',
        'content-type': 'application/x-www-form-urlencoded',
        'authorization': `bearer ${accessToken}`,
        'ConfigCat_': `${configCat}`,
        'cookie': `${cookieValue}`
       }
     }).then((res)=>{
      visitDashboard();
     })
  })

  const visitDashboard = () => {
    cy.visit('dashboard')
  }

图:1

enter image description here

图:2

enter image description here

1 个答案:

答案 0 :(得分:0)

我设法找到了解决问题的方法。由于baseUrl的路径扩展为/auth/login,因此每当我触发cy.request()时,即使凭据正确,它也会始终重定向回登录页面。控制台中也有两个请求。

所以我的方法是在带有cy.request()参数的第一个POST cy.request()之后立即发送另一个带有body参数的GET方法的qs。从请求标头中,我发现每次用户登录时都会提交一个“令牌”。 如果还有另一种简单的方法,请告诉我。

赛普拉斯版本:4.4.0

beforeEach()内,获取“令牌”值;

 beforeEach(() => {
    cy.visit('/');
    cy.loadTokens();
    cy.get('input[name="_token"]').invoke('val').then((val)=>{
        const tokenValue = val;
        cy.loginRequest(tokenValue);
      })
    })

以下是commands.js文件:

Cypress.Commands.add('loginRequest', function (tokenValue) {
     return cy.request({
      method: 'POST',
      url: Cypress.config('baseUrl'),
      followRedirect: true,
      headers: {
        'content-type': 'text/html; charset=UTF-8'
      },
      qs:{
        _token: tokenValue,
        username: 'your_username',
        password:'your_password'
      }
    }).then(()=>{
      return cy.request({
        method: 'GET',
        url: 'https://tenant-demo.somesitedev.net/dashboard',
        followRedirect: false,
        headers: {
          'content-type': 'text/html; charset=UTF-8'
        },
        body:{
          _token: tokenValue,
          username: 'your_username',
          password:'your_password'
        }
      })
    })
  });