1

I'm building an Angular app, and I'm writing unit tests for it. Yay unit tests. I want to mock a particular web service that I'm using (Filepicker.io), which has both a REST API as well as a Javascript API. In my code I use the Javascript API in calls like

filepicker.store(file,
        {    
            options: 'go',
            right: 'here'
        },   
        // filepicker's success callback
        function(resultObject){ 
            // do stuff with the returned object
        }

I know that I could use the $httpBackend provider if I were interacting with Filepicker's REST API, but since my application's code isn't doing that, I'm wondering if/how I could mock an asynchronous API call like this in an Angular unit test.

Do I just override the store method (or the whole filepicker object) in context of my test suite and make it return dummy data of my choosing? That's what they're doing with AngularFire development, with a library that overrides the 'real' Firebase backend service.

Alternately, could I wrap the method in something that uses $httpBackend, so I can use all those handy $httpBackend methods like respond? What's the right strategy here? The first one seems like a simpler and cleaner idea.

Here are some other questions that were similar but ultimately not clear enough for me to fully understand.

AngularJS: unit testing application based on Google Maps API

Unit testing Web Service responses

Mocking Web Services for client layer unit testing

1 Answer 1

2

I would first set your SDK as an injectable Service so it can be used more easily by your angular app

myApp.factory('FilePicker',function(){
   //likely coming from global namespace 
   return filepicker;
})
.controller('ctrl',['FilePicker',function(FilePicker){
    //use File picker
}];

Now you should be able to inject a mock instead of the real implementation for your tests. An example with a our controller

describe('ctrl test', function(){
    var ctrl;

    beforeEach(inject(function($controller){
        var mockService={} // here set up a mock

        ctrl=$controller('ctrl',{FilePicker:mockService});
    }));
});
Sign up to request clarification or add additional context in comments.

1 Comment

It would behoove you to use $window.filepicker, which allows the filepicker service to easily be mocked even if it's directly included somewhere instead of via a service, and also prevents jshint from complaining about global variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.