如何使用 Cypress 和 Auth0 测试单页应用程序

2024-01-01

我有一个单页应用程序隐藏在 Auth0 锁后面,使用@auth0/auth0-spa-js https://github.com/auth0/auth0-spa-js。我想用Cypress来测试一下,所以我决定遵循官方的Auth0 博客文章 https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/以及约翰尼·赖利博客文章 https://blog.johnnyreilly.com/2018/07/cypress-and-auth0.html.

我能够使用建议的请求成功从 auth0 检索有效的 JWT 令牌。我不知道该怎么办:(

我面临的问题是,上述两种方法都依赖于应用程序在本地存储 JWT 令牌(在 cookie 或本地存储中)。这@auth0/auth0-spa-js https://github.com/auth0/auth0-spa-js然而,使用不同的方法,我假设所有相关的 cookie/localstorage 都存储在 auth0 域中。

您知道是否有办法解决它?

已报告类似问题here https://stackoverflow.com/questions/51208998/how-to-login-in-auth0-in-an-e2e-test-with-cypress2018年7月提出,并没有真正提供任何解决方案


我发现了一个已解决的问题@auth0/auth0-spa-jsgithub。这approach https://github.com/auth0/auth0-spa-js/issues/210#issuecomment-539224077建议来自cwmrowe https://github.com/cwmrowe似乎正在工作

解决方案是模拟的响应oauth/token带有在 e2e 测试端生成的令牌的端点。

这种方法似乎对我们有用

我正在复制示例代码cwmrowe https://github.com/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>;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Cypress 和 Auth0 测试单页应用程序 的相关文章

随机推荐