簡體   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