0

I have a scenario where I need to check if the API endpoint was invoked or not.

I tried to use this code but it seems like it is getting always nothing:

let interceptFlag = false

 cy.intercept(`**PATH/${search}/trigger`, (req) => {
   interceptFlag = true
   req.continue((res) => {
      interceptFlag = true
   })
 })

 cy.wrap(interceptFlag).should('eq', true)

I even tried this but always getting nothing:

cy.intercept(`**PATH/${search}/trigger`, cy.spy().as("getSMSCall"));
cy.get('@getSMSCall').should('have.been.called');

I am thinking that there is a delay. May I know how can I put some delay there to wait for the endpoint be invoked and that delay should also be working in the opposite scenario as well, which is API endpoint should not be called.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
simpleMan
  • 1
  • 1

1 Answers1

3

The way to wait for an intercept is to cy.wait() for it's alias.

cy.intercept(`**PATH/${search}/trigger`, (req) => {
   interceptFlag = true
   req.continue((res) => {
      interceptFlag = true
   })
}).as('search')   // add an alias here

// code to trigger the request goes here
cy.visit('/')  // launch a page request
// or
cy.get('button#submit').click()  // send POST request

cy.wait('@search).then(interception => {
  // check the interception here: request and response
})

See documentation at this page: intercept() - Waiting on a request for more details.


API testing pattern

On the other hand, if you are actually testing the API you should NOT use cy.intercept(), instead fire the API request with cy.request() and use .then(...) to wait for it's response.

cy.request('POST', 'http://localhost:8888/users/admin', { name: 'Jane' })
  .then((response) => {
    // response.body is automatically serialized into JSON
    expect(response.body).to.have.property('name', 'Jane') // true
  })

The .then() command will wait for the response to be returned, whereupon you can test the result.

Ref cy.request()