【问题标题】:How to unit test an asynchronus factory which uses another factory in AngularJS?如何对在 AngularJS 中使用另一个工厂的异步工厂进行单元测试?
【发布时间】:2014-05-30 20:44:42
【问题描述】:

我正在尝试为我的 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
   });

 });

我不知道如何模拟所有这些异步调用,并且我无法在网络上找到任何可以转换为我的场景的示例。我也觉得我的代码因为在另一个工厂中被调用而变得更加复杂。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript angularjs unit-testing


    【解决方案1】:

    当你打电话时,比如说 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      相关资源
      最近更新 更多