vendredi 24 juin 2016

AngularJS directive test with $document.bind

I would like to test the code below:

directives.clickAnywhereButHere = ['$document', function ($document) { return { link: function postLink(scope, element, attrs) { var onClick = function (event) { var isChild = element[0].contains(event.target); var isSelf = element[0] == event.target; var isInside = isChild || isSelf; if (!isInside) { scope.$apply(attrs.clickAnywhereButHere) } }; scope.$watch(attrs.isActive, function (newValue, oldValue) { if (newValue !== oldValue && newValue === true) { $document.bind('click', onClick); } else if (newValue !== oldValue && newValue === false) { $document.unbind('click', onClick); } }); } }; }];

HTML is:

<div click-anywhere-but-here="functionA" is-active="checkActive()">

I tried to mock inject $document but not working. How will the unit test be like with Jasmine?

here is my failed test:

beforeEach(inject(function (_$compile_, _$rootScope_, $document) { $compile = _$compile_; $scope = _$rootScope_; $document = $document; }

describe('clickAnywhereButhere', function() { it('should run the expression when click other elements', function () { $scope.isActive = false; $scope.functionA = jasmine.createSpy('functionA'); var elm = angular.element('<div click-anywhere-but-here="editEvidence()">'); $compile(elm)($scope, $document); $scope.$digest(); spyOn($document, 'bind'); $scope.isActive = true; $scope.$digest(); //expect($document.bind()).toHaveBeenCalled() }) });

$document can not be spy on and also isAlert added correctly. Thanks.

Aucun commentaire:

Enregistrer un commentaire