0

我试图拦截一个获取请求并断言有效负载/查询参数是正确的。我已经搜索了 cypress 文档,但提到的所有内容都是设置查询参数。例如,我需要断言诸如https://helloWorld.com/proxy/service具有查询参数 /payload 的fetch 请求?service=request&layers=demo。有没有办法做到这一点?

我已经尝试了几乎所有东西,但与此类似的东西正是我所追求的。有任何想法吗?

cy.location("https://helloWorld/proxy/service").should((loc) => {
             expect(loc.search).to.eq('?service=request&layers=demo')
         })
4

1 回答 1

1

设置拦截可以检查请求的形状

cy.intercept('https://helloworld.com/proxy/service').as('requestWithQuery')

// trigger the request

cy.wait('@requestWithQuery').then(interception => {
  expect(interception.req.body.query.includes('service=request').to.eq(true)
})

我不确定上面的断言是否正是您所需要的,但console.log(interception.req)请检查您需要断言的内容。


拦截也可以指定查询

cy.intercept({
  pathname: 'https://helloworld.com/proxy/service',
  query: {
    service: 'request',
    layers: 'demo'
  },
}).as('requestWithQuery')

// trigger the request

cy.wait('@requestWithQuery')  

顺便说一句,您的使用cy.location()不正确,您将使用

cy.location('search').should('eq', '?service=request&layers=demo')

// or

cy.location().should((loc) => {
  expect(loc.href).to.eq(
    'https://helloworld/proxy/service?service=request&layers=demo'
  )
})

但是该应用程序必须已经导航到https://helloWorld/proxy/service并且您的问题尚不清楚是否正在发生这种情况。


捕捉“helloWorld/proxy/service”

当您的应用使用fetch时,URL 将转换为小写。

所以发送fetch('https://helloWorld/proxy/service')可以被拦截

cy.intercept('https://helloworld/proxy/service') // all lower-case url

赛普拉斯日志中有一条线索,记录的提取显示为全小写字符

(获取)获取 https://helloworld/proxy/service

BaseUrl 和拦截

当 baseUrl 是与拦截主机名不同的域时,您可以使用附加选项指定它,尽管在实践中我发现它也适用于如上所示的完整 URL。

cy.intercept('/proxy/service*', { hostname: 'https://helloworld' })
于 2022-02-18T18:46:12.710 回答