Testing network requests in UI components

Georgii Karataev
2 min readJun 3, 2023

Component testing is an approach in quality engineering that relies on verifying user interface components’ behavior in isolation.

In comparison to unit tests, the implementation details are omitted and assertions are made on the ready-to-use components (framework agnostic). This is a necessary part of any test suite and aims in the first place to catch the bugs that can be visible to users (https://circleci.com/blog/component-vs-unit-testing/). Instead of deploying the whole application and writing an e2e test suite for this scenario, you can render the form’s particular component and do all the checks within only this component.

One of the features of component testing (supported by many testing libraries) is the ability to assert on outgoing network requests.

Example

Imagine the following scenario: users can interact with forms in your web application and you most probably want to test that the form submittion triggers a right request with all the data filled in.

In the form above, we may want to test that when there is a click event on the “Submit” button:

  1. a network request is triggered,
  2. the request has the correct target URL,
  3. the request contains all submitted data.

Using the Cypress library, we can check all of these points above with the following code:

cy.intercept('POST', '/form').as('submitForm');

After mounting the component and filling the fields (skipped in this example), we can finally perform the required click and catch the generated request:

cy.get('button[type="submit"]').click();
cy.wait('@submitForm').its('request.url')
.should('be', 'https://localhost:8081/form');

For asserting on the request’s body we can use:

cy.wait('@submitForm').its('request.body')
.should('eql', {
full_name: 'Jakub Berger',
email: 'jakuberger@info.com',
phone_number: '+420777777777',
prefer_contact: ['email']
});

This way we strictly limited our test to this single URL and the POST method. We also ensured that the URL and body are correct. Since we are mounting the higher-order form component, it is very unlikely that the change in the implementation will lead to a change in the component test.

--

--