Angular 7 Guard Service and Unit Tests

I’m fairly new to Angular 7, (or indeed Angular 2+, having spent the last couple of years doing AngularJS development.

So, in Angular, I’ve created a Guard service which all made sense and was fairly straightforward, however, I found that writing the unit tests was much harder, finding that none of the examples on StackOverflow or on other sites seemed to work with Angular 7.

The code is here:

The guard service

The guard will check whether a user is logged in, and if a claim is passed in, will check whether the user has the claim.

The checkLoggedIn method, first checks the authentication service to see if the user is logged in. If the user is logged in it simply returns true. If the user is not logged in, it saves the desired URL to the authentication service to allow for redirection once the user is logged in, then it navigates to the login page.

The checkClaim method checks whether the currentUser object in the authorisation service has the claim in the claims list.

The unit test

First, we set up a mock ActivedRouteSnapshot and a mock RouterStateSnapshot. In the MockActivatedRouteSnapshot we have the data object that will hold the expectedClaim.

Then we set up the describe block, providing the guard and the ActivedRouteSnapshot.

Logged Out Test

Next the first test, checking that you can’t get to a route that requires authentication if you’re logged out.

So in this test, we’re setting a mock authentication service, that returns false, from checkLoggedIn, and also with the spyOnProperty, we’re telling it to return the expectedClaim = ‘policy’ in the data value of the route.

Logged In Test

Next, checking whether you can get to a route if you’re logged in:

In this test, w’re returning true for the checkLoggedin method, but not requiring a claim.

No claim test

Next, checking that you can’t get to a route that requires a claim you don’t have.

In this test, we’re setting up the authentication service to return true for logged in, and setting the route to require the expectedClaim of ‘policy’, but we’re not adding the that claim to the user.

Valid claim test

Finally, check that you can get to a route that you have a valid claim for.

In this test, we’ve set up the currentUser object in the authentication service to have a claims property, that contains a claim of ‘policy’.