Spying on the Dependency Method

Learn how to use spying on a dependency method, set it up, and use it for unit testing.

We studied how stubbing a dependency is very simple, but it is not always possible. Using a stub is not the only way to isolate logic in a unit test. We don’t have to replace the entire dependency—only the parts our component uses. Replacing certain parts means we point out specific methods on the dependency and assign a spy to them. A spy can answer what we want it to answer, but we can also see how many times it was called and with what arguments. So, a spy gives us much more information about what is happening.

There are two ways to set up a spy in a dependency:

  • Inject the actual dependency and spy on its methods.

  • Use the Jasmine createSpyObj method to create a fake instance of the dependency. We can then spy on the methods of this dependency as we would with the real one.

Setting up the cases

Let’s see how to set up the first case. Consider the following spy.component.ts file, which uses the Title service of the Angular framework:

Get hands-on with 1200+ tech skills courses.