Reputation: 53
I'm using the Cypress intercept command to check certain API calls are made, and now I want to check that only those calls have been made.
There does not seem to be any provision in cy.intercept
to catch excess calls.
How do I define an exact list of api calls and fail the test if actual list does not match expected list, for example
const expectedCalls = [...]
cy.intercept(api).as('api')
cy.wait('@api').should('deep.eq', expectedCalls)
Upvotes: 3
Views: 105
Reputation: 10555
To check for too many calls you can trap the error from the last intercept
// wait for expected calls
expectedCalls.forEach(call => cy.wait('@api'))
// wait once more
Cypress.once('fail', (error) => {
if (error.message.includes('No request ever occurred')) {
// this is ok, don't fail the test
return
}
throw error
})
cy.wait('@fetch') // if this succeeds
.then(() => throw 'Error: too many calls') // then fail the test
Upvotes: 2
Reputation: 31944
One way is to wait for each expected call, then check the number of calls at the end
const expectedCalls = [...]
cy.intercept('api-url').as('api')
cy.visit('/').then(() => {
expectedCalls.forEach(call => {
cy.wait('@api')
.then(intercept => expect(intercept.request.url).to.eq(callUrl)
})
cy.wait(500)
cy.get('@api.all')
.should('have.length', 3)
})
Upvotes: 1