2017-06-14 47 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(); 
     }) 
    }) 
});