Cypress - 使用 google recaptcha 测试联系表

Cypress - testing a contact form with google recaptcha

如何使用 google recaptcha 测试联系表?

我想测试 "We will respond you soon." 消息是否出现。

Cypress 在他们的最佳实践页面上有很好的建议:https://docs.cypress.io/guides/references/best-practices.html#Visiting-external-sites

基本上可以归结为:如果它不是您自己的应用程序,只需存根即可。信任第 3 方测试他们自己的页面。

我创建了自己的 Cypress 命令以测试 Google reCAPTCHA

Cypress.Commands.add('solveGoogleReCAPTCHA', () => {
  // Wait until the iframe (Google reCAPTCHA) is totally loaded
  cy.wait(500);
  cy.get('#g-recaptcha *> iframe')
    .then($iframe => {
      const $body = $iframe.contents().find('body');
      cy.wrap($body)
        .find('.recaptcha-checkbox-border')
        .should('be.visible')
        .click();
    });
});

我将此命令与 Google 给出的说明相结合:

https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do

所以,我不得不对我的源代码做一些小改动:

export const RECAPTCHA_SITE_KEY: string = window.Cypress
  ? '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
  : 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

这对我有用,不需要 cy.wait(500) 或其他固定时间,因为它使用 its 中的赛普拉斯隐式等待加载 iframe 内容。

         cy.get('iframe')
            .first()
            .its('0.contentDocument.body')
            .should('not.be.undefined')
            .and('not.be.empty')
            .then(cy.wrap)
            .find('#recaptcha-anchor')
            .should('be.visible')
            .click();

这也可以作为自定义命令添加。它基于此博客 post:https://www.cypress.io/blog/2020/02/12/working-with-iframes-in-cypress/

经过一番尝试,我想到了这个:

Cypress.Commands.add('confirmCaptcha', function () {
  cy.get('iframe')
    .first()
    .then((recaptchaIframe) => {
      const body = recaptchaIframe.contents()
      cy.wrap(body).find('.recaptcha-checkbox-border').should('be.visible').click()
    })
})

还要确保您的 cypress.json 文件中包含此内容,否则无法访问 iFrame:

"chromeWebSecurity": false