Testing with Angular promises using Jasmine

When dealing with promises while writing tests there are several approaches you can take.

We will start with some specs that just have to consume a promise. You
usually don’t care what the dependency that creates the promise does. If this is the case, create a spy for it.

The following tests for a membership viewer will try to get a list of members from a membership service. The service might need to run some asynchronous code to retrieve the list so it returns a promise instead of the list itself.

Remember that we are only testing the viewer, it does not matter how members are retrieved. We immediately resolve the members promise and simply check if the service was called with the expected parameters.

You might notice that we call an apply every time we expect something returned from the service. This is because a digest is required to resolve the promises even if we return the results right away.

If you really need to track the whole lifecycle of a promise you can make use of a deferred. When you defer a result yourself, you have to make sure your test actually runs up to the point where everything is resolved.

Let’s say you want to indicate that members are being loaded while you wait for the membership service to return a result. The loading state is tracked by a variable called loadingMembers. You now need to take control of the members promise to check that intermediate loading state.

Jasmine provides a done function to help out with testing asynchronous behaviour. You pass it along with a specs’ closure and call it when you are sure everything is done. This way we know that all our expectations are met.

There’s an additional set of third-party Jasmine matchers dedicated to promises. I’d rather go easy on the matchers and just use a simple equal-to when possible. They do call a digest for you but at the same time you lose some control.