Icon for gfsd IntelliJ IDEA

Testing network requests with Cypress

UI system tests with Cypress

We’ve covered the general reasons why we’ve chosen to use Cypress in our previous blogpost about testing. In this next article, we will go into details about how Cypress can be used to run tests for network requests.

The most important step when it comes to fixing bugs is finding a reproducible test to use. For Java, we can use Symflower but in Typescript/Angular using Jasmine, it can be hard to write a reproducible test, which is one of the reasons why we have chosen Cypress for the job.

We’ll start with a basic scenario. Let’s say we noticed that we have a bug, which was caused by a subscription leak that led to multiple backend requests. This can be caused by not unsubscribing from observables.

For example:

this.applicationStore.rootFile$.subscribe((rootFile: File) => {
	...
});

This subscription is bound to the context itself, and if there is no unsubscribe event, during which the component is destroyed, for example, like the above, it may all lead to multiple requests being created.

ngOnDestroy() {
  if (this.rootFileSubscription) {
    this.rootFileSubscription.unsubscribe();
  }
}

We want to avoid having a “quick fix” for our problem, and instead, want to create a test in which we guarantee that these requests will not be called multiple times. This is where Cypress comes into the picture.

it.only('No duplicate network calls', () => {
  cy.intercept('GET', '**/projects/*/files/**').as('fileRequest');
  cy.wait('@fileRequest', { timeout: 10000 });
  cy.get('@fileRequest.all').should('have.length', 1);
});

In the first line, we intercept a GET request with the given matching pattern, and reference it for later use under the name “fileRequest”.

The next line waits for the request to finish, and then we simply check that all matching fileRequests are not matched more than once.

When writing the test itself, first, we get a red one in the TDD fashion. After the fix is done, we can see that it works as intended, and is guaranteed to not occur again in the future.

Testing can be fun, especially if done using the right tools. If you have any thoughts or questions, please feel free to drop us a line at hello@symflower.com. Don’t forget to also subscribe to our newsletter, and follow us on Twitter, Facebook, and LinkedIn for more content.

| 2021-11-04