Unit Testing Routing Events in Angular

Angular’s built-in routing framework is robust, but figuring out how to eloquently test routing events in your app can be tricky. In this post, we will go over a clean and easy way to test routing events using tools already provided by the Angular library, with no third-party libraries required.

Let’s say we have the following service that does some simple routing based on the status code of an HTTPErrorResponse:

Setup

To test our routing events, we’ll use an Angular module designed explicitly for this purpose. To use this module, we must give it an array of Routes similar to what you might see in the AppRoutingModule. We’ll also create a small standalone component to satisfy the Route type requirements.

Standalone Component

Spec Setup

Now that we have a simple standalone component, we can set up our Route array and our RouterTestingModule:

Under the hood, the RouterTestingModule creates a spy implementation of Location. This spy will allow us to see where we are currently routed.

Test

Now that we have configured our RouterTestingModule, we can write a test. Routing events are asynchronous, but Angular has a few more tools to help make testing this easy: fakeAsync and tick. fakeAsync wraps and runs a function in what Angular calls a “fake async zone.” In a fake async zone, we can step through time synchronously with the tick method. Let’s see how a simple test might look:

Notice that after we make a call to the function under test, handleError, we call the tick() method, which will step us through time so that the asynchronous action of the routing should now be “complete.” Next, we use TestBed.inject(Location) to get the instance of Location from the dependency injection system. We can now assert that location.path() is our intended routing destination.

Full Spec File

Testing Routing Events in Angular

Testing routing events in Angular takes a little additional setup. However, it will improve your codebase‘s test coverage and ensure your application operates as intended.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *