Time for a Quick(er) Cypress Visit in Angular

Netanel Basal
Netanel Basal
Published in
2 min readJan 10, 2022

--

There is no doubt that Cypress makes testing easier and more enjoyable. However, Cypress can be quite slow when we have many specs, and we use the visit() command every time.

Each time we call the visit() command, our application will be refreshed and initialized, and it can take a few seconds for the actual test to run.

To make a significant performance boost in our E2E specs, we built a command that takes a route, navigates to a blank page, and returns to our original route. Let’s take a look at how we did it.

To begin with, we need to expose the Angular router navigationByUrl() method to Cypress. If you Google ways to do it, you’ll find something similar to this:

Yes, this code will work. Though, I’m not too keen on it. First, I don’t believe that the application should be aware of Cypress. Secondly, this code isn’t tree-shakable. In this example, there are three lines, but more features can be added over time.

To address the above issues, we’ll use the environments feature of Angular. A module with this functionality will be exposed by an environment.e2e file:

Now we can use the envModules in our application:

This property will be initialized with an empty array in our other environments. On a side note, you can use the same technique to initialize specific environment-dependent modules. For instance, only load dev-tools on development.

We can now create the softVisit() command in Cypress:

The visit() command can now be used only once, and a softVisit() can be used for the rest:

It should be noted that if the feature isn’t isolated and the state persists upon navigation, there are two options — use the visit() command or clean the state before performing the softVisit().

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.