繁体   English   中英

在 cypress 测试中模拟/存根/忽略谷歌 recaptcha v3 请求

[英]mock/stub/ignore google recaptcha v3 requests on cypress tests

我们在测试网站上有许多 recaptcha v3 请求(如 POST: https://www.google.com/recaptcha/api2/reload?k=XXXX )。
这会减慢测试速度并降低它们的稳定性。
Recaptcha 不会在测试环境的服务器上验证,所以我们真的不需要它(直到生产 e2e 测试)。
我们想完全存根请求,但是客户端 js 代码应该接收到一些东西才能使操作起作用。

现在我们使用全局support/index.ts

before(() => {
  cy.log('ignore google recaptcha');
  cy.intercept('POST', '**/*google.com/recaptcha/api2/**', { statusCode: 200, body: `["rresp","",null,null,null,""]` });
});

你知道这个问题的替代/更好的解决方案吗?

我们已经让它与现有的 FE 工具一起工作,这些工具通过使用以下存根调用 recaptcha API。 这允许 FE 代码保持不变,但重新验证始终报告为成功。

不会破坏正确配置的重新验证设置,因为令牌 (FAKE_TOKEN) 将无法通过服务器端验证。 它仅适用于通过执行cy.intercept来模拟 BE 时使用。

请注意,如果向 onload 查询参数传递了除ng2recaptchaloaded以外的任何值,您可能需要更改此存根的最后一行

/**
 * API Compatible Stub for Google Recaptcha V3.
 *
 * Always passes recaptcha checks locally - if this was used in real
 * life setting then the server side verification would fail.
 *
 */
const requestOptions = [];
window.grecaptcha = {
  ready: callback => callback(),
  execute: key => {
    if (requestOptions[key] && requestOptions[key].callback) {
      requestOptions[key].callback("FAKE_TOKEN");
    }
    return Promise.resolve("FAKE_TOKEN");
  },
  getResponse: key => {
    return 1;
  },
  render: (el, options) => {
    requestOptions.push(options);
    return requestOptions.length - 1;
  },
  reset: key => {}
};

// this should be based on the value passed to api.js?onload=<>
// but we hard code it for simplicity
ng2recaptchaloaded && ng2recaptchaloaded(window.grecaptcha);

通过在cy.intercept中将 js 文件加载为缓冲区(通过执行,null )来使用它

export function stubRecaptcha(cy: Cypress.cy) {
  cy.intercept(
    { url: /.*\/recaptcha\/api\.js.*/ },
    {
      fixture: "stub-recaptcha-api.js,null"
    }
  );
}

也分享为这个要点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM