这就是我在 React 中解决这个问题的方法:
1 - 创建一个登录命令:
// cypress/support/commands.js
Cypress.Commands.add('A0login', () => {
Cypress.log({
name: 'loginViaAuth0',
})
const audience = Cypress.env('auth_audience')
const client_id = Cypress.env('auth_client_id')
const scope = 'openid email profile offline_access'
const options = {
method: 'POST',
url: Cypress.env('auth_url'),
body: {
grant_type: 'http://auth0.com/oauth/grant-type/password-realm',
realm: 'Username-Password-Authentication',
username: Cypress.env('DEFAULT_USER'),
password: Cypress.env('DEFAULT_PASSWORD'),
audience,
scope,
client_id,
client_secret: Cypress.env('auth_client_secret'),
},
}
cy.request(options).then(({ body }) => {
const claims = jwt.decode(body.id_token)
const { nickname, name, picture, updated_at, sub, exp } = claims
const { access_token, id_token, token_type, expires_in, refresh_token } =
body
const item = {
body: {
access_token,
audience,
client_id,
id_token,
oauthTokenScope: scope,
expires_in,
refresh_token,
scope,
token_type,
decodedToken: {
claims,
user: {
nickname,
name,
picture,
updated_at,
sub,
},
},
},
expiresAt: exp,
}
window.localStorage.setItem(
`@@auth0spajs@@::${Cypress.env('auth_client_id')}::${Cypress.env(
'auth_audience',
)}::openid email profile offline_access`,
JSON.stringify(item),
)
})
})
此命令发出获取令牌的请求,该令牌稍后被解码并存储在本地存储中。
2 - 您需要将 Auth0 缓存位置设置为“localstorage”
3 - 只需在每个测试服之前执行登录并保留 localStorage:
before(() => {
cy.A0login()
cy.visit('/')
cy.saveLocalStorage()
})
beforeEach(() => {
cy.restoreLocalStorage()
})
afterEach(() => {
cy.saveLocalStorage()
})
在我的例子中,cy.saveLocalStorage() 和 cy.restoreLocalStorage() 都是自定义命令。
您可能会发现的唯一问题是此身份验证是通过“用户名密码”进行的,但如果您只想测试应用程序和组件的功能,那不是什么大问题。