Cypress API 登录不会重定向到主页

问题描述 投票:0回答:1

我不想绕过 UI 登录来节省测试时间。我决定在每个钩子之前编写一个在测试中的块之间进行登录的钩子。登录端点返回以下有效负载结构。

{
    "data": {
        "user": {
          ... 
        },
        "jwt": "...",
        "exp": ,
        "iat": ,
        "refreshToken": "",
        "refreshTokenExp": 
    }
}

应该执行登录的钩子:

    beforeEach(() => {
        cy.request(
            {
                method: 'POST',
                url: 'https://some-page/api/v1/auth/login',
                body: {
                    email: '[email protected]',
                    password: 'password'
                }
            })
            .then((response) => {
                const jwt = response.body.data.jwt;
                const refreshToken = response.body.data.refreshToken;
                const exp = response.body.data.ext;
                cy.wrap(jwt).as('authToken');
                Cypress.env('AUTH_TOKEN', jwt);
                window.localStorage.setItem('jwt', jwt)
                window.localStorage.setItem('refreshToken', refreshToken)
                window.localStorage.setItem('exp', exp)
                cy.visit('/home')
            });
    })

测试

it('Visit /users page with valid authentication', () => {
        cy.get('@authToken').then((authToken) => {
            cy.visit('/users/', {
                headers: {
                    Authorization: `Bearer ${authToken}`,
                }
            });
            cy.url().should('contain', '/users')
        });
    })

POST 请求成功执行,端点返回的所有值都存储在浏览器中,但它测试总是失败,因为重定向从未发生。

我尝试了上述代码的各种版本,其中我存储了更多从登录调用返回的有效负载。将更多数据设置到 localStorage。访问钩子中的相同页面,它会被阻止。

javascript testing automation cypress refresh-token
1个回答
0
投票

您可以尝试将访问移至请求回调之外。 Cypress 有时不喜欢从回调内部向队列添加命令

beforeEach(() => {
  cy.request({
    method: 'POST',
    url: 'https://some-page/api/v1/auth/login',
    body: {
      email: '[email protected]',
      password: 'password'
    }
  })
  .then((response) => {
    ...
  })
  cy.visit('/home')
})
© www.soinside.com 2019 - 2024. All rights reserved.