Learning AngularJS: Testing $resource-based Services without Mocks
View this email in your browser

Learning AngularJS

If you are no longer interested in receiving the Learning AngularJS newsletter, click here to unsubscribe.

Testing $resource-based Services

While working with a client on a NodeJS/AngularJS app, I had to dive in and fix the existing unit tests for some services and factories. Unfortunately, the services were reliant on $resource (also known as ngResource) and were difficult to test because the business logic was buried within the callback functions.

Normally, and what the existing tests tried to do, was to mock the $httpBackend object (which $resource uses) and force the correct callback to be called. Working with $httpBackend was too low-level and I had to ask, what am I really testing here? That $resource works properly and calls the right callback? Or that the callback does the right thing? It was the latter so I needed a new strategy to test the service.

The book "Working Effectively With Legacy Code" suggested splitting the service object into two. One service that uses $resource, and another service that doesn't use $resource but does all that crazy business logic that we need. This let me write two unit test suites; one that mocked out $resource and made sure the callbacks were being called, and the other did not require any mocking, only that I pass in variables to the callback and check the state of the service. Much easier to test overall.

So that's the take-away here: give your services, factories and providers a single responsibility. Move anything related to any other responsibility to a new service or factory. Don't think you have to shove all methods and functions and variables into one factory object!

You can check out the full article (with code) on testing $resource-based services here.

Have a great weekend!

Copyright © 2014 GoAugust, All rights reserved.

unsubscribe from this list    update subscription preferences 

Email Marketing Powered by Mailchimp