Testing $q Promises in Angular… For Realz

There are plenty of resources for testing Angular apps, but one thing I can’t seem to find is a good solution for testing $q promises without mocking the results.

Let’s say you have a service that does some asynchronous work and you would like to test the actual resolved values. Because the $q service is tied to Angular’s digest loop, you can’t simply write a test for it.

There have many articles written about testing $q promises, but I have yet to find a solution that works well and is simple to implement, so I made my own.

My solution is to mock the $q service and make it use the ES2015 Promise object. Below is an example of how this solution can be implemented.

The only caveat to this solution is that the $q.defer() pattern is not accounted for, although it should’t be used anyways.

Happy Testing!

— Bogdan

Show your support

Clapping shows how much you appreciated Bogdan Pshonyak’s story.