我想在打开页面时处理对某些文件的一些请求。在屏幕截图中,您可以看到来自 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')
});
我在文档中没有发现任何关于它的限制,欢迎你的想法:)Cypress :v7.4.0
UPDATE 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(但我没有尝试过)。
第三种方法基于
beforeEach(() => {
Cypress.automation('remote:debugger:protocol', {
command: 'Network.clearBrowserCache'
})
})
关于javascript - 当文件缓存在磁盘上时, Cypress 拦截不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67788002/