如何验证 Cypress 中是否已进行其中一个 api 调用?

问题描述 投票:0回答:2

我想答案一定很简单,但我找不到......

如何验证是否已拨打其中一个电话?

cy.intercept('GET', '/api/v1/url1').as('call1');

cy.intercept('PUT', '/api/v1/url2').as('call2');



cy.get('[data-cy-name="submit"]').click();

使用数组等待验证两个调用是否已完成。

cy.wait(['@call1', '@call2']);
cypress e2e-testing web-api-testing cypress-intercept
2个回答
0
投票

如果您只需要确保至少一个拦截匹配,而不是具体

call1
call2
,您可以 alias 单个请求 为它们提供一个“共享”别名。

cy.intercept('/api/v1/*', (req) => {
  // only alias the request if it includes one of our specified endpoints
  if (req.url.includes('url1') || req.url.includes('url2')) {
    req.alias = 'foo';
  }
})
cy.get('[data-cy-name="submit"]').click();
cy.wait('@foo');

0
投票

您可以在请求的方法和 url 中使用通配符。

这是一个示例测试,您可以使用它来探索选项。

它使用

cy.intercept(routeMatcher, staticResponse)
模式,这样我们就可以存根调用并进行混乱,而无需 404'ing。

cy.intercept({
  method: '*',
  url: '**/api/v1/*',
}, 
{}                   // stubbing for this mini-test
).as('api')


// Fire the GET url1 example
cy.window().then(win => {
  win.fetch('domain/api/v1/url1:abc', {method:'GET'})
})

cy.wait('@api').its('request')
  .should(req => {
    expect(req.method).to.eq('GET')
    expect(req.url).to.contain('/url1')
  })


// Fire the PUT url2 example
cy.window().then(win => {
  win.fetch('domain/api/v1/url2:def', {method:'PUT'})
})

cy.wait('@api').its('request')
.should(req => {
  expect(req.method).to.eq('PUT')
  expect(req.url).to.contain('/url2')
})

如果您想具体只捕获

GET
PUT
,您可以使用正则表达式

cy.intercept({
  method: /GET|PUT/,
  url: '**/api/v1/*',
}, 
{}
).as('api')
© www.soinside.com 2019 - 2024. All rights reserved.