Unit testing a directive, with an embedded ng-include tag.

1,513 views
Skip to first unread message

Greg Gilmore

unread,
May 31, 2013, 1:53:35 PM5/31/13
to ang...@googlegroups.com
Hello all,

I was hoping someone in this group would be able to direct me to a working example of unit testing an AngularJS directive in Karma, with a template that contains an embedded ng-include tag?

Here is the directive

Pawel Kozlowski

unread,
May 31, 2013, 1:56:59 PM5/31/13
to ang...@googlegroups.com
Hi!

Use the $templateCache and fill it in with a desired ng-included
template before running your test.

Cheers,
Pawel
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to angular+u...@googlegroups.com.
> To post to this group, send email to ang...@googlegroups.com.
> Visit this group at http://groups.google.com/group/angular?hl=en-US.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>



--
AngularJS book:
http://www.packtpub.com/angularjs-web-application-development/book
Looking for bootstrap-based widget library for AngularJS?
http://angular-ui.github.com/bootstrap/

Greg Gilmore

unread,
May 31, 2013, 2:03:54 PM5/31/13
to ang...@googlegroups.com
Yeah, I did that and it works, but I was only able to get it to work by hard-coding the HTML content.

beforeEach(inject(function($rootScope, $compile, $injector, $templateCache) {
$templateCache.put('../../views/smart_panel/include/library.html', '<div>Library</div>');
// Declare the directive HTML.
element = angular.element('<smart-sub-panel></smart-sub-panel>');

// Define the root scope.
scope = $rootScope;

// Compile and digest the directive.
$compile(element)(scope);
scope.$digest();
}));

it('should have a template title', inject(function($compile, $rootScope) {
var title = element.find('div');

expect(title.length).toBe(2);
expect(title.eq(1).text()).toBe('Library');
}));

I would like to replace the hard-coded HTML, with the actual template referenced as the first argument to $templateCache.

This all began with the following error:

Error: Unexpected request: GET ../../views/smart_panel/include/library.html

Thanks for your quick reply!

Pawel Kozlowski

unread,
May 31, 2013, 2:25:45 PM5/31/13
to ang...@googlegroups.com
Hi!

On Fri, May 31, 2013 at 8:03 PM, Greg Gilmore <greg.g...@mac.com> wrote:
> Yeah, I did that and it works, but I was only able to get it to work by
> hard-coding the HTML content.

I don't think it is a good idea to shoot real xhr request under unit
tests. Your current approach is OK.

Cheers,
Pawel
Reply all
Reply to author
Forward
0 new messages