Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing directives that uses templates

How can i unit test directives that use templateUrl to load templates?

Since $httpBackend is a mock, it will not load templates either. I would like to be able to use something like

$httpBackend.whenGET(/^\/views\//).passThrough();

and let it actually get the templates, but I haven't figured out how to do this correctly.

I think I have something confused regarding how to unit test directives. Disclaimer: I have no experience testing, or using jasmine nor testacular.

Any help is appreciated.

like image 685
Kenneth Lynne Avatar asked Mar 02 '13 19:03

Kenneth Lynne


Video Answer


1 Answers

IMO the easiest way of testing directives that depend on templates (referenced by the templateUrl) is to put those templates in the $templateCache up-front. Usually this is done by the build process.

In more details: each template markup is converted to the JavaScript code and put into the $templateCache. Also, a AngularJS module is generated (with a name of a module being path to a template).

By applying this technique we've got only JavaScript files to deal with and we don't need to mock any HTTP calls. The downside is that you need an additional build step.

I believe that originally this technique was popularized by the excellent repository by Vojta Jina: https://github.com/vojtajina/ng-directive-testing where you can see templates preparation here and the actual test referencing a module with a template preload here.

like image 138
pkozlowski.opensource Avatar answered Oct 06 '22 21:10

pkozlowski.opensource