MOCK AN API RESPONSE USING INTERCEPT

Cypress is a testing tool that greatly improves your testing experience. It offers features such as:

● Debuggability, Debug directly from familiar tools like Chrome DevTools. Our readable errors and stack traces make debugging lightning fast

● Real-time reloads, Cypress automatically reloads whenever you make changes to your tests. See commands executed in real-time in your app.

● Automatic waiting, Never add waits or sleeps to your tests. Cypress automatically waits for commands and assertions before moving on - No more async hell.

● Spies, stubs, and clocks, Verify and control the behavior of functions, server responses, or timers. The same functionality you love from unit testing is right at your fingertips.

● Consistent results, Our architecture doesn’t use Selenium or WebDriver. Say hello to fast, consistent and reliable tests that are flake-free.

● Network traffic control, Easily control, stub, and test edge cases without involving your server. You can stub network traffic however you like.

● Screenshots and videos, View screenshots taken automatically on failure, or videos of your entire test suite when running headlessly.

Getting Started

With any new node base project, we must initialize using NPM.

npm init -y

Once we have the package.json file, we can start with cypress installation.

cd /your/project/path
npm install cypress --save-dev

This will install Cypress locally as a dev dependency for your project.

Intercept

Cypress helps you test the entire lifecycle of HTTP requests within your application. Within Cypress, you have the ability to choose whether to stub responses or allow them to actually hit your server. You can also mix and match within the same test by choosing to stub certain requests, while allowing others to hit your server.

Mocking enables one to decouple the back-end from the front-end which results in faster execution of tests. In cypress, we can mock any XHR (XML HTTP Request) using

cy.intercept().

Intercepting a network request using Cypress is known as a spy. It allows you to monitor network traffic based on a supplied URL. More than just monitoring, spies can be expanded upon to stub responses or even make assertions

The restful-booker application has provided a few free rest API’s that I am using here for demonstration purposes.

Let’s take a look at the request url https://www.demoqa.com/BookStore/v1/Books

This API calls to a books endpoint to fetch the book details. Lets begin with hitting this API to get the current book details available in the store. Here is the cypress code to call the API

This will give us the following details. Where we can see a total of 8 book's details are retrieved.

Now we will intercept this API call in order to set up a spy. Selecting this request will provide us with information that we can use to begin crafting a spy We should set an alias for our request for better visibility within the test runner

With the above code snippet, now we can run our test to verify the spy correctly monitored network traffic to the books endpoint.

Now that we have set up a spy successfully, Here you can see the list of book’s details in the right panel. Let's try to manipulate the request. We manipulate this request and will display only one books details on hitting the same URL

Stubbing Response

Stubs are useful in building test state within an end-to-end test by simulating data which may or may not directly affect the test.

Why do we need a stub??

● The UI is developed but the backend is not ready and we need to test the data on the UI

There are two option to solve this problem

1. Wait for backend developers to finish their work and then start testing

2. Stub the data

books.json contains the mocked data which would go in the /fixtures folder

We can stub this data by providing a fixture to the intercepted request. This will replace the response body with the JSON data provided into the books.json file which we have to keep within the fixture folder.

With this code now our table will populate a single book entry instead of a list of books. We were successfully able to mock the response

The fetch request now has an open circle, to indicate that it has been stubbed. Also, note that the alias for the cy.intercept() is now displayed on the right-hand side of the Command Log. If you mouse over the alias, you can see more information about how the request was handled.

Conclusion

One of the major difficulties of frontend testing is being able to control the data that is displayed on the page, which is not always the most reliable. As with the intercept option we can mock responses, calls to those outside services in our e2es to ensure that bad test data isn’t the thing holding us back from completing our functionality testing.

Another difficulty with frontend testing is error handling. Cypress simplifies matters considerably. With the intercept option we can mock responses, with errorcodes as well. This grants us the capability to test how the site holds up against different errorcodes without having to start doing weird things inside the database or the infrastructure of our application.

Last updated

Was this helpful?