Unit Testing AngularJS and PouchDB Service

别来无恙 提交于 2019-12-12 19:19:09

问题


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!


回答1:


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';
       }
});


来源:https://stackoverflow.com/questions/22591994/unit-testing-angularjs-and-pouchdb-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!