PBr*_*own 2 javascript testing cypress cypress-intercept
有什么方法可以让 Cypress 捕获任何未使用cy.intercept处理和存根的请求。我希望 Cypress 返回一个有用的错误,以突出显示发出未存根请求的实例。目前它只是让这些请求通过,这没有什么帮助。
如果有一种方法可以保证处理程序是链中的最后一个处理程序,那么它的架构方式将允许使用一个包罗万象的处理程序,但看起来没有任何方法可以做到这一点。
这在技术上是可行的,这里有一个演示测试可以玩。
我的模式基于这样的前提:拦截是在最后定义的基础上处理的(忽略中间件类型),因此包罗万象的内容是在所有其他内容之前定义的。
包罗万象用作*匹配器,它将捕获绝对所有内容,但仅限于那些尚未被另一个拦截捕获的内容。
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')
})
})
Run Code Online (Sandbox Code Playgroud)
笔记
如果你想将其应用到现实世界的应用程序中,这个策略并不是万无一失的。
我使用上面的方法expect(unstubbedRequests.length).to.eq(2)是因为我知道会有两个未捕获的请求,并且.should()如果发送请求有一些延迟(此模拟中没有任何延迟),该命令将重试。
为了解决这个问题,在您的测试中,您需要在检查unstubbedRequests数组之前提供某种等待方式
cy.wait(some-maximum-time)或者
但如果等待时间不够长,这些等待方法可能会不稳定。
这是试图在测试中证明阴性的结果。
理想情况下,您希望最终测试“知道”将发送的所有请求,但作为临时测试开发工具,此技术可能很有用。