How to test a component that uses the ActivatedRoute class in Angular?
Hey everyone,

Not a while ago I had to write some tests to a component which used the ActivatedRoute class to check some query params in order to do some logic and it took me quite some time until I figured out a solution in order to mock the ActivedRoute class. Because of that, I decided to write this little tutorial as documentation and I hope it helps someone in the future who has the same doubt.
Alright, for this example will be using Jest as out test framework.
So, let’s imagine that we have an Angular application that will make an API request to get some data and based on the response it will use the angular router to navigate to another component passing some information through queryParams. An example of a component with this logic is shown bellow:
Now, let’s see an example of the implementation of the someComponent which will access the information from the queryParams through the ActivatedRoute class.
Nice, now that we have these components set up, how can we test the someComponent? In order to do so, we will need to mock the ActivatedRoute class so we can provide some fake information in the test that will simulate the same behavior on our component. So, let’s do that.
If we look into the documentation of the ActivatedRoute class we will note that the queryParams is an Observable that has type of Params.

Now that we know what is the queryParams we can try to mock it in our test. One way of doing it is shown below:
What we are doing in the example above is creating a class which has a property called queryParams that is an Observable. With this observable, we are defining an object called urlParams which has a property called type. By doing so, we are creating a class that mocks the same behaviour implemented in the ActivatedRoute class.
Now that we have our mock class ready, we can provide it to Jest so when it see the ActivatedRoute instance on the someComponent it will use the mock class instead of the actual ActivatedRoute class which is not instantiated.
Let’s see how we can finally write the basic test of the someComponent.
And that is it guys. Now you can test your component that makes use of the ActivatedRoute class. I hope this tutorial helps you!
Nice coding!!