i have angular directive following snippet of code, how unit test this?
link: function($scope, ielm) { $(ielm).on('paste', function(){ $timeout(function(){ $scope.lastscan = date.now(); }); }); }
you need use $timeout.flush() instantly call $timeout callbacks have defined, makes synchronous code testing purposes.
try this:
app.js
app.directive('mydirective', function($timeout){ return function($scope, ielm) { // no need use jquery ielm.bind('paste', function(){ console.log('**paste**') $timeout(function(){ console.log('timeout') $scope.lastscan = date.now(); }); }); // $(ielm).on('paste', function(){ // $timeout(function(){ // $scope.lastscan = date.now(); // }); // }); } }); appspec.js
describe("my directive", function() { var element, $timeout, $compile, $scope; // load module has directive beforeeach(module('plunker')); beforeeach(inject(function(_$timeout_, _$compile_, _$rootscope_) { $timeout = _$timeout_; $compile = _$compile_; $scope = _$rootscope_.$new(); })); function compileelement(){ // use $compile service create instance of directive // can test against element = $compile('<my-directive></my-directive>')($scope); // manually update scope $scope.$digest(); } it("defines 'lastscan' property", function() { compileelement(); // trigger paste event element.triggerhandler('paste'); // angular doesn't know paste event need // manually update scope $scope.$digest(); // call $timeout callback // removing asynchronous awkwardness $timeout.flush(); // assert directive has added property scope expect($scope.lastscan).tobedefined(); }); });
Comments
Post a Comment