Testing With Dependencies

Learn how to test code with dependencies using stubbing and spying.

In this lesson, we will look at a more advanced scenario for testing a component with dependencies.

In a real-world scenario, components are not usually as simple as AppComponent. They will almost certainly be dependent on one or more services. We have different ways of dealing with testing in such a situation. One thing is clear, though: if we are testing the component, then we should not test the service as well. So, when we set up such a test, the dependency should not be the real thing. There are different ways of dealing with that when it comes to unit testing; no solution is strictly better than another:

  • Stubbing: This is the method of telling the dependency injector to inject a stub of the dependency that we provide instead of the real thing.

  • Spying: This is the method of injecting the actual dependency but attaching a spy to the method that we call in our component. We can then either return mock data or let the method call through.

Note: Using stubbing over spying is preferable when a dependency is complicated. Some services inject other services into their constructor, so using the real dependency in a test requires us to compensate for other dependencies.

Regardless of the approach, we ensure that the test does not perform unintended actions, such as talking to a filesystem or attempting to communicate via HTTP; we are testing the component in complete isolation.

Replacing the dependency with a stub

Replacing a dependency with a stub means that we completely replace the dependency with a fake one. We can create a fake dependency in the following ways:

  • Create a constant variable that contains properties and methods of the real dependency.

  • Create a mock definition of the actual class of the dependency.

The approaches are not so different. In this section, we will look at the first one. Feel free to explore the second one. Consider the following stub.component.ts component file:

Get hands-on with 1200+ tech skills courses.