Unit testing a conditionally rendered isolate scope directive

517 views
Skip to first unread message

David Gee

unread,
Apr 17, 2014, 4:03:18 PM4/17/14
to ang...@googlegroups.com
I've been writing unit tests for angular controllers and services for a while now, but been putting off the daunting task of testing directives. 
I currently have an isolated scope directive, with an external controller that handles a flag which determines if the directive is rendered or not, via an ng-if on the directive's root element. The directive is for a "flash messages" style notifications system. I can't figure out how to set up the test correctly to default the flag to be true.

There's a simple jsFiddle here:

Removing the "ng-if" from the directive template causes the test to pass. The test still fails if you change the template to use 'ng-if="true"'.

Charlie

unread,
May 24, 2014, 9:00:36 AM5/24/14
to ang...@googlegroups.com
I'm hitting the wall on this one too.

Charlie

unread,
May 27, 2014, 11:17:06 AM5/27/14
to ang...@googlegroups.com
See Igor's response below:

Hi Charles,

here is a working test: http://jsfiddle.net/mWrq9/2/

The issue is that there too much stuff happening on the root node of your template. You are compiling the element directive and also replaces itself with a template and that template contain ngIf, which also replaces the root element. If you just wrap the component into  a testing div and then compile the div, the div will become the root of your template and then things will work.

Alternative solution is not to use "replace: true" option in the directive. We are deprecating that option in 1.3 and won't support it in 2.0 because it wrecks havoc in the DOM and causes all kinds of state issues like the one in your test.

cheers,
Igor

On Thursday, April 17, 2014 4:03:18 PM UTC-4, David Gee wrote:
Reply all
Reply to author
Forward
0 new messages