首页 > 解决方案 > 赛普拉斯 AWS Cognito 集成

问题描述

Cypress 有没有办法与 Cognito 集成?我有一个没有登录页面的应用程序,但使用来自另一个具有 Cognito 登录名的网站的 cookie。(使用cookies)

无论如何都可以从第三方应用程序“登录”而不访问该页面?我还尝试向登录端点发出 API 请求,这也给了我一个跨域问题。

任何想法表示赞赏!

标签: amazon-cognitocypress

解决方案


Cypress 提供创建自定义命令的能力,可用于执行 Amplify/Cognito 命令。例如,在测试经过身份验证的页面时,我使用登录命令而不是使用 UI 登录,因为这被认为是一种反模式

如果您能够获取 cognito 配置,则可以使用自定义命令执行登录,如下所示。

在 cypress/support/commands.js 中创建自定义命令

import Amplify, { Auth } from 'aws-amplify';
Amplify.configure({
  Auth: {
    mandatorySignIn: true,
    region: "eu-west-1",
    userPoolId: Cypress.env("userPoolId"),
    identityPoolId: Cypress.env("identityPoolId"),
    userPoolWebClientId: Cypress.env("appClientId"),
    oauth: {
        domain: Cypress.env("domain"),
        scope: ['email', 'profile', 'aws.cognito.signin.user.admin', 'openid'],
        redirectSignIn: Cypress.env("redirect"),
        redirectSignOut: Cypress.env("redirect"),
        responseType: 'code',
        options: {
            AdvancedSecurityDataCollectionFlag: false
        }
    }
  }
});

Cypress.Commands.add("login", (email, password) => {
  return Auth.signIn(email, password)
      .then(user => {
        console.log('===> user', user);

        let session = Auth.currentSession();

        console.log('===> session', session);
      })
      .catch(err => console.log('===> err', err));
})

在规范文件中使用 cy.login() 命令:

describe('Authenticated page test', () => {
  it('should be logged in', () => {
    cy.login('test.user@email.com', 'Password')
    
    cy.visit('/')
    cy.contains('some page content')
  })
})

推荐阅读