2016-07-21 5 views
2

私はカスタムディレクティブでアイソレートスコープを使用しています。私はplunkerリンクを更新しました。 http://plnkr.co/edit/NBQqjxW8xvqMgfW9AVek?p=preview 誰かがscript.jsファイルの単体テストケースを記述するのに手伝ってもらえますか?ディレクティブ内でスコープとタイムアウト関数のユニットテストケースを書く方法

script.js

var app = angular.module('app', []) 
 

 
app.directive('myDirective', function($timeout) { 
 
    return { 
 
    restrict: 'A', 
 
    scope: { 
 
     content: '=' 
 
    }, 
 
    templateUrl: 'my-directive.html', 
 
    link: function(scope, element, attr) { 
 

 
     $timeout(function() { 
 
     element = element[0].querySelectorAll('div.outerDiv div.innerDiv3 p.myClass'); 
 
     var height = element[0].offsetHeight; 
 
     if (height > 40) { 
 
      angular.element(element).addClass('expandable'); 
 
      scope.isShowMore = true; 
 
     } 
 
     }) 
 

 

 
     scope.showMore = function() { 
 
     angular.element(element).removeClass('expandable'); 
 
     scope.isShowMore = false; 
 
     }; 
 

 
     scope.showLess = function() { 
 
     angular.element(element).addClass('expandable'); 
 
     scope.isShowMore = true; 
 
     }; 
 
    } 
 
    } 
 
})

(function() { 
 
    'use strict'; 
 

 
    describe('Unit testing directive', function() { 
 
    var $compile, scope, element, compiledDirective, $rootScope, $timeout; 
 

 
    beforeEach(module("app")); 
 
    beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_) { 
 
     $compile = _$compile_; 
 
     scope = _$rootScope_.$new();   
 
     $timeout = _$timeout_; 
 
     element = angular.element(' <div my-directive content="content"></div>'); 
 
     compiledDirective = $compile(element)(scope); 
 
     scope.$digest(); 
 
    })); 
 

 
    it('should apply template', function() { 
 
     expect(compiledDirective.html()).toBe(''); 
 
    }); 
 

 
    it('check for timeout', function() { 
 
     $timeout.flush(); 
 
    }); 
 

 
    }); 
 
})();

答えて

0

使用する$ timeout.flush()$のタイムアウトのためのテストケースを作成するための機能

it('check for timeout', function() { 

    scope.digest(); 

    // flush timeout(s) for all code under test. 
    $timeout.flush(); 

    // this will throw an exception if there are any pending timeouts. 
    $timeout.verifyNoPendingTasks(); 

    expect(scope.isShowMore).toBeTruthy(); 
}); 

Check this article for better understanding.

関連する問題