如何使用赛普拉斯和Auth0测试单页应用程序 [英] How to test single page application with Cypress and Auth0
问题描述
我正在使用 @ auth0/auth0-spa隐藏在Auth0锁后面的单页应用程序-js .我想使用赛普拉斯对其进行测试,因此我决定遵循官方 Auth0博客帖子,以及Johnny Reilly
I am having a single page application hidden behind Auth0 lock, using @auth0/auth0-spa-js. I would like to test it using Cypress, so I have decided to follow the official Auth0 blog post, as well as Johnny Reilly blog post.
我能够使用建议的请求从auth0成功检索有效的JWT令牌.我不知道该怎么办:(
I am able to successfully retrieve valid JWT token from auth0 using suggested request. I have no idea what to do with it :(
我面临的麻烦是以上两种方法都依赖于应用程序将JWT令牌本地存储(在cookie或localstorage中).但是, @ auth0/auth0-spa-js 使用的是另一种方法,并且我假设所有相关的cookie/本地存储都存储在auth0域中.
The trouble I am facing is that both of the above approaches are relying on the app to store the JWT token locally (either in cookie or localstorage). The @auth0/auth0-spa-js is, however, using a different approach, and I assume all the relevant cookies/localstorage is stored on auth0 domains.
您有什么想法,是否有办法解决?
Do you have any idea, if there is a way to get around it?
此处有类似的问题于2018年7月提出,但并未提供任何解决方案
There is a similar issue reported here raised in July 2018, not really providing any solution
推荐答案
我在@auth0/auth0-spa-js
github上找到了已解决的问题.
I found a resolved issue on @auth0/auth0-spa-js
github. The approach suggested by cwmrowe seems to be working
解决方案是使用e2e测试端生成的令牌来模拟oauth/token
端点的响应.
The solution is to mock the response of oauth/token
endpoint with token generated on e2e test side.
这种方法似乎对我们有用
The approach seems to be working for us
我正在复制示例代码 cwmrowe
Cypress.Commands.add(
'login',
(username, password, appState = { target: '/' }) => {
cy.log(`Logging in as ${username}`);
const options = {
method: 'POST',
url: Cypress.env('Auth0TokenUrl'),
body: {
grant_type: 'password',
username,
password,
audience: Cypress.env('Auth0Audience'),
scope: 'openid profile email',
client_id: Cypress.env('Auth0ClientId'),
client_secret: Cypress.env('Auth0ClientSecret')
}
};
cy.request(options).then(({ body }) => {
const { access_token, expires_in, id_token } = body;
cy.server();
// intercept Auth0 request for token and return what we have
cy.route({
url: 'oauth/token',
method: 'POST',
response: {
access_token,
expires_in,
id_token,
token_type: 'Bearer'
}
});
// Auth0 SPA SDK will check for value in cookie to get appState
// and validate nonce (which has been removed for simplicity)
const stateId = 'test';
const encodedAppState = encodeURI(JSON.stringify(appState));
cy.setCookie(
`a0.spajs.txs.${stateId}`,
`{%22appState%22:${encodedAppState}%2C%22scope%22:%22openid%20profile%20email%22%2C%22audience%22:%22default%22}`
);
const callbackUrl = `/auth/callback?code=test-code&state=${stateId}`;
return cy.visit(callbackUrl);
});
}
);
declare namespace Cypress {
interface Chainable<Subject> {
login(
username: string,
password: string,
appState?: any
): Chainable<Subject>;
}
}
这篇关于如何使用赛普拉斯和Auth0测试单页应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!