2016-07-21 2 views
2

schreiben Ich verwende isolieren Bereich in benutzerdefinierten Anweisung. Ich habe den Link zu Plunker aktualisiert. http://plnkr.co/edit/NBQqjxW8xvqMgfW9AVek?p=preview Kann mir jemand beim Schreiben des Unit-Testfalls für die script.js-Datei helfen?Wie Einheit Testfall für Gültigkeitsbereich und Timeout-Funktion innerhalb der Direktive

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(); 
 
    }); 
 

 
    }); 
 
})();

Antwort

0

Verwenden $ timeout.flush() -Funktion für Testfall für $ timeout

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(); 
}); 
Schreib

Check this article for better understanding.

Verwandte Themen