Reputation: 338
Using cy.intercept() to intercept (and stub) a couple of network requests (to google tag manager), but would like to test at an early point in my test before I expect them to be called.
How would I test that the 2 routes I'm intercepting haven't been called yet?
Thanks!
Upvotes: 6
Views: 11872
Reputation: 745
You could take advantage of the cy.spy
command:
cy.intercept('/my-route', cy.spy().as('myRequest'));
// later in the test
cy.get('@myRequest').should('not.have.been.called'); // not yet intercepted
// something triggers the API call
cy.get('@myRequest').should('have.been.calledOnce'); // now is intercepted
See: https://docs.cypress.io/api/commands/spy
Credits to: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#check-if-the-network-call-has-not-been-made
Upvotes: 16
Reputation:
Intercept has a routeHandler section which can be a function
cy.intercept(routeMatcher, routeHandler?)
routeHandler (string | object | Function | StaticResponse)
The function receives the request, and inside that another function can receive the response,
see Intercepting a response
cy.intercept('/integrations', (req) => {
// req.continue() with a callback will send the request to the destination server
req.continue((res) => {
// 'res' represents the real destination response
// you can manipulate 'res' before it's sent to the browser
})
})
so either on the receipt of req
or the inner function on receipt of res
, set an external flag and test it at one or more places in the test,
// top of the test
let interceptFlag = false;
cy.intercept('/my-route', (req) => {
interceptFlag = true;
req.continue((res) => {
// or here
interceptFlag = true;
})
})
// later in the test
cy.wrap(interceptFlag).should('eq', false); // not yet intercepted
// something triggers the API call
cy.wrap(interceptFlag).should('eq', true); // now is intercepted
This is very generalized, if you post some details can be more specific.
Upvotes: 3