I am sure most of you have encountered a problem that made you use ViewChild to come up with a solution. I am not going to explain what ViewChild does in Angular. Just to give an idea for novices, it is a method to pass data from child to parent component. For more information, you can visit this link from the official documentation of Angular 👇:
Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers…
In one of my assignments, I also had to use ViewChild decorator as a private variable in my component. And things started getting muddled when it came to writing unit tests. In this article, I will try to explain step by step how to unit test a private ViewChild.
Let’s get started 🚀,
I assume you have a component looks similar to this, where you use the private ViewChild:
First, we need to stub the child component (btw, there are also other solutions to mock your method for unit testing. I will go for stubbing 🤖). The steps that we will follow are basically these:
- In our spec file for our parent component, we need to create a stub component for our child component.
- In this stub component, we need to provide the original child component itself, and we need to use a custom class that we created particularly for this stub (we are not going to use our child component’s original class).
- We need to define the method that we are going to use from child component and mock it in this custom class.
- We need to declare our stub component together with the parent component in our declarations.
- Finally, we need to create an instance of the child component as a stub. There is a tricky part of this step. While creating the instance, you should use the parent component as “any”, because the ViewChild that we are testing is private. Otherwise, it will not allow you to unit test it.
So I created a spec file that contains all these steps in it 🥳. And tried to add comments to make it clear. Finally, our spec file should look something like this:
Now you are all set and good to go 🎊. I hope it was useful for your project.
Good luck with the tests 🙂
May the code be with you!