Cypress - 使用 google recaptcha 测试联系表

srg*_*rgj 5 recaptcha cypress

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

我想测试一下“我们会尽快回复您”。消息出现。

小智 13

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

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()
    })
})

Run Code Online (Sandbox Code Playgroud)

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

"chromeWebSecurity": false
Run Code Online (Sandbox Code Playgroud)


amo*_*rez 7

我创建了自己的 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();
    });
});
Run Code Online (Sandbox Code Playgroud)

我将此命令与 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';
Run Code Online (Sandbox Code Playgroud)