angularjs - How to Unit test an angular directive that has a bind('error', function(){})? -


I have an angle instruction that changes the image source of an element if the file does not exist and 404 is returned here This is:

> myApp.directive ('fallbacksrc', function) {var fallBackSrc = {link: function postLink} (element, element, attrs) {element.bind ('error', function ( ) {Angular.element (this) .attr ("src", '/images/image-not-available.png');})}}} return decline backscr;}]);

It does the required work but now I am trying to test this instruction to the unit, how will I trigger 'error' that this function is bound in Jasmine?

To test it, you will need to spy on element.bind and use the Jasmines 2.0 function

So in my example, I have added a placeholder image as a replacement image, so that it can cause an error.

  angular.module ('components', []). Directive ('Fallbacksrc', function () {var fallBackSrc = {link: function postLink (area, element, attrs) {element.bind ('error', function) (angular.element (this) .attr ("src" 'Http: //placehold.it/350x150');});}} returnbacks backscr;});  

And in the test we return to spyOn element.bind and error < Pre> detective (element, 'bind'). And. Throwanewal ('Error');

In addition to this, we need to use the work done to run the specs, which it has to do with setTimeOut .

requires testing of asynchronous functions in the test.

Description ('Directive: fallback SRC', function () (describe that 'image does not exist', function () {var element, radius; first (module ('components')); first each (injection ($ Root scope, $ COLLECTION) {element = angular.element (" & gt; '); Intelligence (element,' bind ' ) .and.returnValue ('error'); scope = $ rootsecope; $ compilation (scope); scope. $ Digest ();}); ("location holder must be img src", function (done) {SetTimeout (function () {console.log (element.attr ('src')); (Element.attr ( 'src')) was .toqual ( 'http://placehold.it/350x150'); ();}, 2000);});}); });

Comments