javascript - 当文件缓存在磁盘上时, Cypress 拦截不起作用

标签 javascript testing caching cypress end-to-end

我想在打开页面时处理对某些文件的一些请求。在屏幕截图中,您可以看到来自 cypress 面板的日志:
cypress log
为了处理这些请求,我添加了如下代码:

    it('Check intercept', () => {
        cy.intercept('/settings.json').as('settings');
        cy.intercept('/static/model/*').as('plates');

        cy.visit('/editor/ckpdx02f7098c08632il2aetr');

        cy.wait('@settings')
        cy.wait('@plates')
    });
它适用于 settings.json , 但使用 .stl文件没有
enter image description here
如果我这样写它也行不通:
    it('Check intercept', () => {
        cy.intercept('/settings.json').as('settings');
        cy.intercept('/static/model/ckpdwtgpg096g08636kd57n39/plate_4.stl').as('plate4');
        cy.intercept('/static/model/ckpdwtgpg096g08636kd57n39/plate_3.stl').as('plate3');
        cy.intercept('/static/model/ckpdwtgpg096g08636kd57n39/plate_2.stl').as('plate2');
        cy.intercept('/static/model/ckpdwtgpg096g08636kd57n39/plate_1.stl').as('plate1');
        cy.intercept('/static/model/ckpdwtgpg096g08636kd57n39/plate_0.stl').as('plate0');

        cy.visit('/editor/ckpdx02f7098c08632il2aetr');

        cy.wait('@settings')
        cy.wait('@plate4')
        cy.wait('@plate3')
        cy.wait('@plate2')
        cy.wait('@plate1')
    });
我在文档中没有发现任何关于它的限制,欢迎你的想法:)
Cypress :v7.4.0UPDATE 1:我发现了更多细节:如果打开 chrome 开发人员工具并在“网络”选项卡中禁用缓存-它总是可以正常工作UPDATE 2:我在演示库中创建了一个问题:https://github.com/cypress-io/cypress/issues/16766

最佳答案

fetch()协议(protocol),磁盘缓存读取未被 cy.intercept() 捕获.
您可以更改 fetch()在应用程序中关闭缓存,

fetch("http://127.0.0.1:2000/plate.stl", {cache: "no-store"});
但如果您更喜欢在测试中执行此操作,请将其添加到规范的顶部
beforeEach(() => {
  const disableCache = (win) => {
    const original = win.fetch;
    win.fetch = (...args) => original(...args, {cache: "no-store"});
  }
  cy.on('window:before:load', win => disableCache(win))
})
注意,通常你可以像这样修改拦截中的标题
cy.intercept("/plate.stl", req => {
  req.headers['cache'] = 'no-store'
})
但似乎拦截与缓存读取不匹配,因此它永远不会到达那一点。

附带说明一下,您使用 Cypress v4.12.0 的工作分支使用 xhr 而不是 fetch。如果您将 xhr 方法替换到 Cypress v7.4.0 构建中(仍然使用拦截),问题就会消失。
这意味着你也可以通过使用旧的 fetch polyfill 来解决这个问题,它可以即时将 fetch 转换为 xhr(但我没有尝试过)。

第三种方法基于
  • 本次讨论 Using Chrome Debugger Protocol from Cypress
  • 示例配方 offline-spec.js
  • 引用 Network.clearBrowserCache

  • beforeEach(() => {
      Cypress.automation('remote:debugger:protocol', {
        command: 'Network.clearBrowserCache'
      })
    })
    

    关于javascript - 当文件缓存在磁盘上时, Cypress 拦截不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67788002/

    相关文章:

    javascript - 如何根据属性的总和来组织对象数组?

    javascript - 如何检查浏览器是否缓存了特定资源(例如图像)?

    testing - IBM 的 Rational Functional Tester (v 9.1) 是否测试网页?

    hibernate - Hibernate 二级缓存和 Spring 3.1 的 @Cacheable 的合适用例是什么?

    javascript - 如何在版本更改时重新加载资源(HTML/CSS/JS)

    android - 在 android 中退出时清除应用程序缓存

    c# - 从 c#/asp.net 打开 HTML 页面

    javascript - 理解 Javascript 中的 this 关键字

    ruby-on-rails-3 - Rack::Test 使用 JSON 的 PUT 方法无法将 JSON 转换为参数

    testing - 圈复杂度边