Question

I am attempting to unit test my individual Angular factories but am having a hard time trying to correctly mock and inject the PouchDB object. My factory code is currently as follows:

factory('Track', [function() {
    var db = new PouchDB('tracks');
    var resource = {
        getAll: function() {
          return db.allDocs({include_docs: true});
        }
    return resource;
}]);

I had tried to use Angular's $provide service to inject a mock PouchDB instance with no luck:

 module(function($provide) {
    $provide.value('PouchDB', {
        allDocs: function() {
            return 'MOCKED';
        }
    });

I am not entirely sure where to go from here. Any help would be greatly appreciated!

Was it helpful?

Solution

As just stated in the comments: you have to wrap the global variable PouchDB inside a service to make it injectable. This is due to Angular doing DI via simple function-parameters. So just do something like:

  angular.module('myModule')
     .factory('PouchDBWrapper', function(){
         return PouchDB;
     }

Then you can inject it into your Track factory:

 factory('Track', [function(PouchDBWrapper) {
   var db = new PouchDBWrapper('tracks');
   var resource = {
      getAll: function() {
         return db.allDocs({include_docs: true});
      }
    return resource;
}]);

and in your test you can mock it by:

module(function($provide) {
   $provide.factory('PouchDBWrapper', {
       allDocs: function() {
           return 'MOCKED';
       }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top