首页 > 解决方案 > 让赛普拉斯正确登录到 Auth0

问题描述

我使用 cypress 设置了一套 E2E 测试。我有一个反应打字稿应用程序,我正试图让它与柏树一起工作。我面临的主要问题是我使用 Auth0 作为我的身份验证提供程序。这意味着我需要在每次测试之前以编程方式登录用户。但是我似乎无法得到正确的方法来做到这一点。当我尝试它调用回调 url 但它似乎没有对用户进行身份验证,因为他们只是转到一个空白页面?我正在使用 @auth0/auth0-react 包,它有一个用于访问所有 Auth0 数据的钩子。

赛普拉斯命令:

import jwt_decode from 'jwt-decode';

Cypress.Commands.add('login', () => {
    cy.log(`logging in as ${Cypress.env('auth_username')}`);

    cy.request({
        method: 'POST',
        url: Cypress.env('auth_url'),
        body: {
            grant_type: 'password',
            username: Cypress.env('auth_username'),
            password: Cypress.env('auth_password'),
            audience: Cypress.env('auth_audience'),
            scope: 'openid profile email',
            client_id: Cypress.env('auth_client_id'),
            client_secret: Cypress.env('auth_client_secret'),
        },
    }).then(({ body }) => {
        const claims = jwt_decode(body.id_token);
        const { nickname, name, picture, updated_at, email, email_verified, sub, exp } = claims;
        const item = {
            body: {
                ...body,
                decodedToken: {
                    claims,
                    user: {
                        nickname,
                        name,
                        picture,
                        updated_at,
                        email,
                        email_verified,
                        sub,
                    },
                    audience: Cypress.env('auth_audience'),
                    client_id: Cypress.env('auth_client_id'),
                },
            },
            expiresAt: exp,
        };
        window.localStorage.setItem('auth0Cypress', JSON.stringify(item));
    });
});

标签: typescriptcypressauth0react-tsx

解决方案


推荐阅读