问题描述
我想在打开页面时处理对某些文件的一些请求。在屏幕截图上,您可以看到来自 cypress 面板的日志:
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
文件
如果我这样写也行不通:
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')
});
我在文档中没有发现任何关于它的限制,欢迎您的想法:)
赛普拉斯:v7.4.0
UPDATE 1:
我发现了更多细节:如果打开 chrome 开发者工具并在“网络”选项卡中禁用缓存 - 它始终可以正常工作
UPDATE 2:
我在演示存储库中创建了一个问题:https://github.com/cypress-io/cypress/issues/16766
解决方法
使用 fetch()
协议,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 来解决这个问题,该 polyfill 将 fetch 即时转换为 xhr(但我还没有尝试过)。
还有第三种方式基于
beforeEach(() => {
Cypress.automation('remote:debugger:protocol',{
command: 'Network.clearBrowserCache'
})
})
,
如有疑问,请添加额外的 *
。
cy.intercept('**/static/model/**/*').as('plates')
领先于 **
的任意数量的前面部分,例如 https://my-domain/static...
子目录的尾随 /**
和文件名的尾随 /*
。