如何在 Cypress 12 中隐藏 fetch 和 XHR 日志?

Dᴀʀ*_*ᴅᴇʀ 5 typescript cypress

我正在学习 Cypress 12,想禁用 fetch 和 XHR 的日志记录。在我的研究中,我发现“隐藏 XHR 对 Cypress 测试运行程序的调用”指出了这一点,但由于某种原因,它不起作用。

我的以下步骤:

根级别tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": [
      "cypress",
      "node",
      "cypress-real-events",
      "cypress-file-upload",
      "cy-verify-downloads"
    ],
    "baseUrl": "./"
  },
  "include": ["**/*.ts", "./cypress/support/cypress.d.ts"]
}
Run Code Online (Sandbox Code Playgroud)

目录树:

/ 
  tsconfig.json
  package.json
  yarn.lock
  cypress.config.ts
  / cypress
    / support
      / cypress.d.ts
      / e2e.ts
Run Code Online (Sandbox Code Playgroud)

cypress.d.ts的内容:

declare namespace Cypress {
  interface ResolvedConfigOptions {
    hideXHRInCommandLog?: boolean;
  }
}
Run Code Online (Sandbox Code Playgroud)

e2e.ts的内容:

// Hide fetch/XHR requests from command log
if (Cypress.config('hideXHRInCommandLog')) {
  const app = window.top;
  if (
    app &&
    !app.document.head.querySelector('[data-hide-command-log-request]')
  ) {
    const style = app.document.createElement('style');
    style.innerHTML =
      '.command-name-request, .command-name-xhr { display: none }';
    style.setAttribute('data-hide-command-log-request', '');

    app.document.head.appendChild(style);
  }
}
Run Code Online (Sandbox Code Playgroud)

仍然呈现 XHR:

在此输入图像描述

这似乎是进一步研究中的一个已知问题:

在 Cypress 12 中如何隐藏 XHR 并获取日志?

Fod*_*ody 7

在 Cypress 信息面板中有这个答案隐藏 URL

我尝试了一下,这是适用于简单的 1-fetch 测试的变体。

注释掉 看看Cypress.on("log:changed")它会失败。

Cypress.on("log:changed", (log, interactive) => {
  if (log.displayName !== "fetch") return;

  const logs = window.top.document.querySelectorAll("li.command-name-request");
  if (logs.length) {
    const last = [...logs][logs.length - 1];
    last.remove();
  }
});

it("tests that fetch logs are removed from Cypress UI", () => {

  cy.intercept("https://jsonplaceholder.typicode.com/todos/1").as("fetch");

  cy.visit("/");

  cy.wait("@fetch").then(() => {
    cy.wrap(window.top.document)
      .its("body")
      .find('[data-cy="reporter-panel"]')
      .find("li.command-name-request")
      .should("not.exist");
  });
});
Run Code Online (Sandbox Code Playgroud)

您还必须修补 XHR 类型,我还没有测试那么远。应该是这样的

if (log.displayName !== "fetch" && log.displayName !== "xhr") return
Run Code Online (Sandbox Code Playgroud)


Ala*_*paz 6

您可以在测试顶部使用拦截来关闭fetch和 的日志记录xhr

cy.intercept({ resourceType: /xhr|fetch/ }, { log: false })
Run Code Online (Sandbox Code Playgroud)

参见路由匹配器

resourceType - 请求的资源类型。有关resourceType 可能值的列表,请参阅“请求对象属性”。

{
  ...
  resourceType: 'document' | 'fetch' | 'xhr' | 'websocket' | 'stylesheet'
             | 'script' | 'image' | 'font' | 'cspviolationreport' | 'ping'
             | 'manifest' | 'other'
}
Run Code Online (Sandbox Code Playgroud)