I need to write unit tests for an AngularJS service that utilizes $resource
. I want to keep it isolated by using Jasmine's spyOn to spy on the query()
method of $resource
. In my controller, I prefer to use the shorter form of query()
where you pass success and error functions directly to the query method without having to call $promise.then(success, error)
. Is this achievable or am I required to stick with the longer form of
query().$promise.then(success, error)
?
Here is a plunker I set up with a failing test demonstrating my issue: http://plnkr.co/edit/hVc2YNnwUDNv7IHODOMD?p=preview
I have come across several StackOverflow posts proposing solutions, but they are based on older versions of the components I am utilizing. From the plunker link, you can see that I am working with Angular 1.5.2 and Jasmine 2.4.1.
On a related note, many tutorials demonstrate that in your controller, you can simply assign the return value of query()
to an array, which will automatically update as the data loads. While this is a clean approach, what happens if an error occurs? My assumption is that if there is an issue loading the data, either a default error message appears, or nothing happens at all. Is the best practice to handle errors elsewhere using an interceptor and possibly trigger an event to notify the user in a generic, non-controller-specific manner? In such a case, the interceptor would need a way to determine the appropriate message to display to provide context – for example, 'Loading of Bagels seems slower than normal; click here to retry' instead of just displaying '500 status code returned.'