26.09.2024 Views

How to use Cypress Intercept to Stub API Responses

Cypress provides a complete package for End to End automation, it can help you with UI automation, API automation and web application automation. Cypress is a Unique tool it makes all the tasks associated with test automation very easy and doable, In addition to that it can provide you a functionality called Intercept which helps in mocking or stubbing the request and its associated response.

Cypress provides a complete package for End to End automation, it can help you with UI automation, API automation and web application automation. Cypress is a Unique tool it makes all the tasks associated with test automation very easy and doable, In addition to that it can provide you a functionality called Intercept which helps in mocking or stubbing the request and its associated response.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4. Aliasing and waiting:

After performing an intercept we can use the concept of aliasing using

‘.as()’ for the intercepted request and put a wait contention until it gets

completed.

cy.intercept('GET', '/api/data').as('getData');

// Perform actions that trigger the GET request

cy.wait('@getData');

Prerequisite for Cypress Intercepts?

For performing cypress Intercept operation few basic things are required

such as cypress installed and working, understanding of network request

and responses and commands like (HTTPS,PUT,POST,GET,DELETE).

Understanding of java script is also required for performing scripting .

Cypress Intercepts implementation

Here we are intercepting functionality and setting a response which will be

coming from the fixture file.

In the below example we are trying to describe how to perform cypress

intercept cy.intercept(). Firstly we need a request whether it is

GET/PUT/POST and we need to create a fixture file where we will be

storing the response which we want to send when the request comes in.

In the later part of the code we are using aliasing “.as(‘getPosts’)” the

request that it can be used further. After that we will be visiting the web

application and performing an action which later creates a GET request

and then we wait for it to get intercepted and then we send the response

which we have stored inside the fixture.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!