Unit Testing Private ViewChild in Angular

Ammar Merakli
2 min readMay 21, 2020

--

I am sure most of you have encountered a problem that made you use ViewChild to devise 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 👇:

In one of my assignments, I used 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 that looks similar to this, where you use the private ViewChild:

First, we need to stub the child component (btw there are other solutions to mock your method for unit testing. I will go for stubbing 🤖). The steps that we will follow are these:

  1. In our spec file for our parent component, we need to create a stub component for our child component.
  2. 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).
  3. We need to define the method that we are going to use from the child component and mock it in this custom class.
  4. We need to declare our stub component and the parent component in our declarations.
  5. 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 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!

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ammar Merakli
Ammar Merakli

Responses (2)

Write a response