2017-06-14 69 views
0

我有一個下面的代碼段(簡體):單元測試AngularJs茉莉:然後 - 捕測試問題

angular 
.module('myApp') 
.controller('MyController', MyController); 

function MyController(wordService) { 

    getWord(); 

    function getWord() { 

     return wordService.getNextWord() 
      .then(doSomethingWithWord) 
      .catch(doSomethingFailure); 

     function doSomethingWithWord(response) { 
      // ... something 
     } 

     function doSomethingFailure() { 
      // ... failing 
     } 
    } 
} 

我就來測試一下。 ? 我這個奮鬥過了一天,現在我無法得到它的工作:(

如何測試該代碼

回答

0

對於未來,我想通了: 我必須使用$ q服務和要求角度消化循環。

describe('MyController', function() { 

    var $controller, myController, wordService, $q, deferredResponse, scope; 

    beforeEach(function() { 
     module('myApp'); 
     inject(function(_$controller_, _wordService_, _$q_, $rootScope) { 
      $controller = _$controller_; 
      wordService = _wordService_; 
      scope = $rootScope.new(); 
      $q = _$q_; 
     }); 
     myController = $controller('MyController', {wordService:wordService}); 

     deferredResponse = $q.defer(); //deferring asynchronous response 
     spyOn(wordService, 'getNextWord').and.returnValue(deferredResponse.promise); 
    }); 

    describe('Testing WordService', function() { 
     it('Should get next word', function() { 
      deferredResponse.resolve({status: 200, data: {word: 123}}); 
      scope.$apply(); 

      expect(wordService.getNextWord).toHaveBeenCalled(); 
     }) 
    }) 
});