Angular Unit Testing pt.4

Angular Unit Testing

Set Up

If you do not already have a basic Angular CLI project, check out Installing Angular CLI

Basic Debugging of Unit Tests

Continuing from the third article in this series, we are now set up to debug the individual unit tests to see if our variables contain the proper values, or why tests may be failing.
We will be using VSCode. Ensure you have Debugger for Chrome installed. In VSCode, Click Debug, then Install Additional Debuggers:

Open VSCode and create a Book model that will contain the results from our service mock data

Open registration component and have getResults call the registrationService to get books to register

If there are results, we want to set the results variable and call showResults

In VSCode, open registration component tests and create a test for the getResults function:

There are a few modifications to be able to mock the registration service in the test class

Be sure to include all of the imports at the top, specifically the service and “of” to return the data

registrationServiceMock – represents our mock of the service that we set on line 27

registrationServiceStub – acts as the actual service which returns resultsData, the mock data

spyon – used to check if a function was called and provide a custom value.  In this case we are mocking a call for the registrationService.getBooks function.  When we call the component’s getResults function, it mimics the call to registrationService.getBooks and the registrationServiceStub returns our mock data.

expect – takes a value to test against another value or state

Open a command prompt and go to working directory

Cd C:\proj\tutorials\unittests\angular-testing

Type command to execute tests

ng test

You should see all tests passed:

Now let’s open the Chrome debugger – Hit F12 and you should see this:

Type “debugger;” in the registration.component.ts file, getResults method:

Save the file and the browser will refresh and rerun the tests.  But now it will break into the debugger on that line

If you hover over the data variable, you will see its current value, which includes the single book mock data from the unit test.  You can also see it in the Scope section at the bottom

Click step over icon  Twice

You can see that since we have data, we step into the first IF to call showResults

You can also set a breakpoint in this view by clicking to the left of the line number, example line 33

With this breakpoint, we can step through other areas without having to add “debugger;” to the code

You can imagine how this simple debugging can be extremely helpful if a test is failing and it is difficult to identify the reason at first glance.

More information on Angular testing