【发布时间】:2021-01-05 10:10:57
【问题描述】:
对于我的应用程序,我尝试通过 API 而不是 UI 登录
我需要存储 accessToken 以浏览应用程序
我目前的登录方式是这样的
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 存储到资源文件中。我已经尝试了各种方法,例如这里,但没有成功
谢谢
编辑:
我已经尝试过了,但仍然没有运气
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);
});
});
编辑:这最终对任何感兴趣的人都有效
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);
});
});
【问题讨论】:
-
嗨。您只需阅读请求响应并将令牌保存到
sessionsStorage。顺便说一句,我认为(在这种情况下)将有效负载声明为const,然后将其分配给cy.request,这不是最好的方法。直接设置为请求体cy.request({ ... }).its('body.token').then(token => { window.sessionsStorage.setItem('accessToken', token) }) -
Cypress.Commands.add('login', (overrides = {}) => { cy.request({ method: 'POST', url: Cypress.env('auth_url'), body : { 用户:{ 电子邮件:Cypress.env('auth_username'),密码:Cypress.env('auth_password'), } } }) .its('body.token') .then((token) => { window .localStorage.setItem('accessToken', token); }); });像这样?我得到了
-
重试超时:cy.its() 出错,因为属性:令牌在您的主题上不存在。 cy.its() 等待指定的属性标记存在,但它从未存在。如果您不希望属性令牌存在,则添加一个断言,例如:cy.wrap({ foo: 'bar' }).its('quux').should('not.exist')
-
嘿,不一定是
body.token,也可以是body.access_token。您必须从响应中找出正确的路径/结构。此外,我确实建议将您的令牌存储在sessionStorage中,以便在会话完成时将其清除。 -
我的答案与这个答案相匹配。所以,请看这个stackoverflow.com/a/59016663/14910874
标签: typescript oauth-2.0 cypress