首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Cypress Cypress 2.0中存储访问令牌

在Cypress Cypress 2.0中存储访问令牌
EN

Stack Overflow用户
提问于 2021-01-05 18:10:57
回答 1查看 285关注 0票数 1

对于我的应用程序,我尝试通过API而不是UI登录

我需要存储在应用程序中导航的accessToken

我当前的登录方法如下所示

代码语言:javascript
复制
 Cypress.Commands.add('login', (overrides = {}) => {
  Cypress.log({
    name: 'loginViaAuth0',
  });

  const options = {
    method: 'POST',
    url: Cypress.env('auth_url'),
      headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
      username: Cypress.env('auth_username'),
      password: Cypress.env('auth_password'),
    }
  }

  cy.request(options);
});

我需要将accessToken存储到资源文件中。我尝试过像这里这样的各种方法,但都没有成功

Set local storage in Cypress

谢谢

编辑:

我试过了,但还是不走运

代码语言:javascript
复制
 Cypress.Commands.add('login', (overrides = {}) => {
  cy.request({
    method: 'POST',
    url: Cypress.env('auth_url'),
    body: {
      user: {
        email: Cypress.env('auth_username'),
        password: Cypress.env('auth_password'),
      }
    }
  })
    .its('token')
    .then((token) => {
      window.localStorage.setItem('accessToken', token);
    });
});

编辑:这对任何感兴趣的人来说最终都是有效的

代码语言:javascript
复制
Cypress.Commands.add('login', (overrides = {}) => {
cy.request({ 
    method: 'POST', 
    url: Cypress.env('auth_url'), form: true, 
    body: { grant_type: 'client_credentials', scope: 'xero_all-apis' ,
           username: Cypress.env('auth_username'), 
           password: Cypress.env('auth_password'), } }) 
    .its('body') 
   .then(res => { 
     cy.setLocalStorage('accessToken',res.accessToken);
   }); 
});
EN

回答 1

Stack Overflow用户

发布于 2021-01-07 12:07:09

@Steven983,请尝试这个

代码语言:javascript
复制
Cypress code Cypress.Commands.add('login', () => { 
cy.request({ 
    method: 'POST', 
    url: Cypress.env('auth_url'), form: true, 
    body: { grant_type: 'client_credentials', scope: 'xero_all-apis' }, 
    auth: { 
           username: Cypress.env('auth_username'), 
           password: Cypress.env('auth_password'), } }) 
    .its('body') 
   .then(res => { 
     cy.log(res.body.accessToken) //To verify token is shown in console
     cy.setLocalStorage('accessToken', res.body.accessToken); 
   }); 

});

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65576848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档