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.
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
1. Intercepting Network Requests:
We can use “cy.intercept()” for intercepting network requests and
responding to them back as per the requirements from the test.
In the below snippet cypress is intercepting a GET request which is coming
to ‘/api/inters’ and responds back with the data stored in fixture file named
as ‘inter.json’
cy.intercept('GET', '/api/inters, { fixture: 'inter.json' }).as('getInter');
2. Modifying responses:
We can perform modification in the intercepted request and responses.
In the below snippet cypress is intercepting a request with PUT command
for updating a user and it is responding back with a modified response
having updated user data.
Copy
cy.intercept('PUT', '/api/users/1', (req) => {
req.reply({ statusCode: 200, body: { id: 1, name: 'Updated User' } });
}).as('updateUser');
3. Stubbing/Mocking Requests:
Using intercept we can perform stubbing, with the help of stub network
requests we can prevent requests to reach the network. In place of that it
can be redirected to a stubbed server and from there it can get the
response which is mocked by the user.
cy.intercept('POST', '/api/login', {
statusCode: 200,
body: { token: 'mocked-token' },
}).as('loginRequest');