2016-12-05 38 views
0

我真的很驚訝,不知道發生了什麼事,什麼可能是解決方案...我正在測試這段代碼。 .then永遠不會被稱爲!:

describe('PicturesSvc.updatePicturesList', function() { 
    beforeEach(module('com.myapp')); 

    it('download and update pictures list', function (done) { 
     inject(function ($q, PicturesSvc, PicturesRemoteSvc) { 
      console.log($q); 
      var localPictures = []; 
      var remotePictures = [ 
       { 
        id: 'A', 
        likes: 2, 
       }, 
      ]; 

      $q(function (resolve, reject) { 
       console.log('going to resolve promise...'); 
       resolve(remotePictures); 
      }) 
       .then(function (val) { 
        console.log('Great! Promise has been resolved!', val); 
        done(); 
       }) 
       .catch(function (err) { 
        console.log('Something went wrong... :(', err); 
        done(err); 
       }); 

      var deferred = $q.defer(); 
      deferred.resolve('Test again!'); 
      deferred.promise 
       .then(function (result) { 
        console.log(result); 
       }); 
    }); 

}); 

輸出爲以下之一:

LOG: function Q(resolver) { ... } 
LOG: 'going to resolve promise...' 

    PicturesSvc.updatePicturesList 
    ✖ download and update pictures list 

Finished in 4.926 secs/5.01 secs 

SUMMARY: 
✔ 0 tests completed 
✖ 1 test failed 

FAILED TESTS: 
    PicturesSvc.updatePicturesList 
    ✖ download and update pictures list 
     PhantomJS 2.1.1 (Mac OS X 0.0.0) 
    Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. 
+0

嘗試交換整個構造函數到'$ q.resolve(remotePictures).then(...)' –

回答

2
在角

爲了resolve你還需要調用$scope.$apply()

更多在這裏承諾:https://docs.angularjs.org/guide/unit-testing#testing-promises

+0

因爲它是服務,它也可以用'$ rootScope。$ apply()':)來完成https://docs.angularjs.org/api/ng/service/$q#testing – Miquel

+0

有沒有什麼辦法鏈接promise?現在我已經意識到第二個'.then'中的promise沒有被調用(首先'.then'在服務中,所以在那裏做'$ rootScope。$ apply()'是沒有意義的)。 – Miquel