Photo by Daniel von Appen on Unsplash

Angular Component Class Tests

When testing Angular components, I almost exclusively use component class tests. These are tests that do not use the TestBed and allow you to test a component the same way you would test a service.

The main reason I prefer component class tests is that they are much easier to write than using the TestBed. They don’t require you to setup a test module. Simply call the constructor of the class under test and you’re ready to go! Does your component depend on some services? Simply create stub functions or Jasmine spies and inject them into the constructor in a beforeEach function. This pattern should be familiar to any developer coming from a Java or C# background.

Using the TestBed allows you to inspect your component’s template and assert against the DOM and its bindings. But is this really necessary in unit tests? In my opinion, DOM interaction should be relegated to high level UI tests using tools like Cypress or Selenium.

I’ve included a sample component with corresponding component class test to illustrate the following scenarios:

  • Testing a property of the class
  • Testing an output property emits the expected value
  • Testing a service is called with the expected value