RKS
RKS

Reputation: 21

Cypress stubbing XHR response based on request

I am beginer in Cypress and looking for help with network stubbing. My UI tiggers 3 API calls concurrently upon clicking on a button in the UI. All 3 API are of same endpoint, BUT each of them have different request and response.

I am able to stub the json response using cy.fixture, cy.server() and cy.route(). My need is to 'only stub the 3rd XHR call response', but, my test stubs all three because of the same endpoint.

Any suggessions on how could I test it using any condition ? example - Only stub the call if the parameters of 'request'XHR is 'XXX'? I tried using before and after the .click() of submit button but that didn't work.

cy.fixture('myfixture').then(jsonresponse => {
function FixtureController(request, response) {
                    if (cy.url().request.body.contains("XXX")) {
                        cy.server()
                        cy.route('POST', 'URL', jsonresponse).as('myalias')

I appreciate any support.

Thanks!

Upvotes: 2

Views: 1335

Answers (1)

agoff
agoff

Reputation: 7145

You can use cy.intercept to match based on several things, including query parameters.

cy.intercept({
  url: 'http://example.com/search*',
  query: { q: 'expected terms' },
}, { fixture: 'myfixture' } )

If you need to match on the request body contents, you can use a route handler to specify.

cy.intercept('http://example.com/search*', (req) => {
    if (req.body.contains('some string') {
        req.reply({ statusCode: 200, fixture: 'myfixture' });
    } else {
        req.reply(); // not providing any input forwards the request as normal
    }
});

Check out the cy.intercept documentation for more info.

Upvotes: 1

Related Questions