Angular Material Unit Test with mdSidenav

In this tutorial, we will be creating unit tests for a controller that uses $mdSidenav. The reason why I am picking this one up is because $mdSidenav service is different from usual angular services.


Why did I say this? Because $mdSidenav returns a function, not a service object like usual services. Well, there are other services that are functions, i.e. $filter. Anyway, hopefully this tutorial will give you an idea on how to write unit tests when you are dealing such services.

The controller to be tested

Below is the source code of the controller that uses $mdSidenav.

The unit tests

Many people will go straight and create a unit test like below

There is nothing wrong with the test above, but the problem is how do we finish the test, so we can verify the behavior of the $scope.close() function? You probably have already known that we need to spy on the $mdSidenav.close() function, but how?


There are actually 2 ways of doing so (that I am aware of). One is replace the original service via $provide, the other way is inject a fake service when creating a controller instance.

Via $provide

We can use $provide service to register a fake object or function with the same name, in this case it is $mdSidenav, to replace the original service.

So the fake object gets automatically injected into controller when we instantiate it. i.e.

Manual injection

We can also create a spy and then inject it via the $controller constructor, like below.

Finish the test

The spy has now been setup. You may wonder the purpose of sideNavCloseMock when you were going through above code. It should be all clear if you see below code. Let’s finish the test.

It is as simple as that! Hopefully you get the idea of how to create mocks or setup spies for situation like this.



Wayne Hong

Passionate Java full stack developer.