如何使用 Cypress 测试 AWS Amplify Angular Authenticator 组件?

Rob*_*son 2 testing amazon-web-services angular cypress amplify

我希望能够在像这样的 cypress 测试中将测试输入“键入”到 AWS Amplify Authenticator 组件(amplify-authenticator)中:

describe('My Authenticator Test', () => {
  it('should let me type in the username field', () => {
    cy.visit('http://localhost:8100/');

    cy.get('amplify-authenticator')
      .find('input#username')
      .type('sample@example.com');
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我可以检查元素并看到它:

在此处输入图片说明

Cypress 测试无法找到输入字段。

如何使用赛普拉斯访问“用户名”字段(以及其他类似字段)?

Rob*_*son 5

因为 AWS Amplify Authenticator 是一个带有“shadow DOM”的组件,我们需要通过编辑 cypress.json 文件并为“experimentalShadowDomSupport”添加一个条目来在 Cypress 中启用 Shadow Dom 支持,如下所示:

{
  "supportFile": "cypress/support/index.ts",
  "experimentalShadowDomSupport": true
}
Run Code Online (Sandbox Code Playgroud)

现在我们可以在我们的测试中搜索 Shadow DOM 中的组件,如下所示:

describe('My Authenticator Test', () => {
  it('should let me type in the username field', () => {
    cy.visit('http://localhost:8100/');

    cy.get('amplify-authenticator')
      .shadow()
      .get('amplify-sign-in')
      .shadow()
      .find('amplify-form-section')
      .find('amplify-auth-fields')
      .shadow()
      .as('amplifyAuthFields');

    cy.get('@amplifyAuthFields')
      .find('amplify-username-field')
      .shadow()
      .find('amplify-form-field')
      .shadow()
      .find('input#username')
      .type('sample@example.com');

    cy.get('@amplifyAuthFields')
      .find('amplify-password-field')
      .shadow()
      .find('amplify-form-field')
      .shadow()
      .find('input#password')
      .type('Password123');
  });
});
Run Code Online (Sandbox Code Playgroud)

在这里,我使用了 Cypress Aliases 来重用选择器链的一部分。

因为您会经常这样做,所以最好将身份验证器驱动代码抽象为自己的 Cypress 自定义命令。