如何对在AngularJS中使用另一个工厂的异步工厂进行单元测试?

时间:2014-05-30 20:44:42

标签: javascript angularjs unit-testing

我正在尝试为我的databaseContacts工厂编写一些单元测试,我很遗憾如何实际编写它们,因为存在许多复杂情况。

这是我要测试的工厂:

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

这是getDatabaseContactsFromDB:

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

这是我为测试设置的尝试:

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

   it ('should get database contacts', function (){
     //somehow call databaseContacts.getContacts() and nicely mock the return data
   });

 });

我没有掌握如何模仿所有这些异步调用,而且我还没有能够在网络上找到任何可以转换到我的场景的示例。我还觉得我的代码因在另一家工厂内被调用而变得更加复杂。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

当你打电话时,让我们说getContacts,你必须刷新$ httpBackend,你必须模拟对该URL的响应,如下所示:

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()
相关问题