javascript - How to unit test an asynchronus factory which uses another factory in AngularJS? -


i trying write unit tests databasecontacts factory, , lost how write them, there number of complications.

here factory want test:

 .factory('databasecontacts',     function (getdatabasecontactsfromdb ){       return {        getcontacts: function(){          var dbcontacts = getdatabasecontactsfromdb.query();          return dbcontacts.$promise.then(function(result){            return result;          });        },        removecontact: function (contact){          getdatabasecontactsfromdb.remove(contact);        },        addcontact: function (contact){          var addedcontact =  getdatabasecontactsfromdb.save(contact);          return addedcontact.$promise.then(function(result){            return result;          });        }      };  }) 

and here getdatabasecontactsfromdb:

 .factory('getdatabasecontactsfromdb', function ($resource){    return $resource('http://localhost:8000/contacts/');  }) 

here's attempt @ setup test:

 describe( 'databasecontacts service', function(){    var databasecontacts, httpbackend;    beforeeach(function() {      module('app.contacts');       inject (function ($httpbackend, _databasecontacts_){        databasecontacts = _databasecontacts_;        httpbackend = $httpbackend;      });    });    aftereach(function(){      httpbackend.verifynooutstandingexpectation();      httpbackend.verifynooutstandingrequest();    });     ('should database contacts', function (){      //somehow call databasecontacts.getcontacts() , nicely mock return data    });   }); 

i don't have grasp on how 1 mock of these asynchronous calls, , haven't been able find examples on web can translate on scenario. feel code further complicated having factory being called within factory. appreciated.

when call, let's getcontacts, you'll have flush $httpbackend , have mock response url this:

var storeddata; databasecontacts.getcontacts().then(function(data) {    storeddata = data; }); httpbackend.expect('get', 'http://localhost:8000/contacts/').respond(<mocked_json_here>) httpbackend.flush() expect(storeddata).tobedefined() 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -