gpt4 book ai didi

javascript - 使用 cy.intercept 时捕获未处理的请求

转载 作者:行者123 更新时间:2023-12-03 07:53:31 25 4
gpt4 key购买 nike

有没有办法让 Cypress 捕获任何未使用 cy.intercept 处理和 stub 的请求。我希望 Cypress 返回一个有用的错误,以突出显示发出未 stub 请求的实例。目前它只是让这些请求通过,这没有什么帮助。

如果有一种方法可以保证处理程序是链中的最后一个处理程序,那么它的架构方式将允许使用一个包罗万象的处理程序,但看起来没有任何方法可以做到这一点。

最佳答案

这在技术上是可行的,这里有一个演示测试。

我的模式基于这样的前提:拦截是在最后定义的基础上处理的(忽略中间件类型),因此包罗万象的内容是在所有其他内容之前定义的。

catch-all 使用 * 作为匹配器,它将捕获绝对所有内容,但仅捕获那些尚未被另一个拦截捕获的内容。

it('catching unstubbed requests', () => {

const unstubbedRequests = []
cy.intercept('*', (req) => unstubbedRequests.push(req))

// these requests I have stubbed already
cy.intercept('https://jsonplaceholder.typicode.com/todos/1', {stub:1}).as('stub1')
cy.intercept('https://jsonplaceholder.typicode.com/posts/1', {stub:2}).as('stub2')

// make some calls on the app window, simulating real app calls
cy.window().then(win => {
win.fetch('https://jsonplaceholder.typicode.com/todos/1') // should stub
win.fetch('https://jsonplaceholder.typicode.com/posts/1') // should stub
win.fetch('https://jsonplaceholder.typicode.com/users/1') // should not stub
win.fetch('https://jsonplaceholder.typicode.com/photos/1') // should not stub
})

cy.wait('@stub1')
cy.wait('@stub2')
cy.wrap({}).should(() => {
expect(unstubbedRequests.length).to.eq(2)
expect(unstubbedRequests[0].url).to.eq('https://jsonplaceholder.typicode.com/users/1')
expect(unstubbedRequests[1].url).to.eq('https://jsonplaceholder.typicode.com/photos/1')
})
})

注释

如果您想将其应用到现实世界的应用程序中,此策略并非万无一失。

上面我使用了 expect(unstubbedRequests.length).to.eq(2) 因为我知道会有两个未捕获的请求,并且 .should() code> 如果发送请求有一些延迟,命令将重试(此模拟中没有任何延迟)。

为了解决这个问题,在您的测试中,您需要在检查 unstubbedRequests 数组之前提供某种等待方式

但是如果等待时间不够长,这些等待方法可能会不稳定。

这是试图在测试中证明否定的结果。

理想情况下,您希望最终测试“知道”将发送的所有请求,但作为临时测试开发工具,此技术可能很有用。

关于javascript - 使用 cy.intercept 时捕获未处理的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76582264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com