Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Testing angular directive with [^form] dependency

I am trying to test a directive, as explained e.g. here http://angular-tips.com/blog/2014/06/introduction-to-unit-test-directives/.

However, in my directive I use form, so I have this in my directive declaration object:

        return {
            link: link,
            restrict: 'E',
            require: ['^form'], // <- I have this !!
            scope: { //...
            },
            controller: function ($scope) {
            //...
            }
        };

as such, when I execute the usual prerequisite for my Jasmine test

element = '<mydirective/>';
element = $compile(element)(scope);

I am getting following dependency problem when trying to run karma / Jasmine test:

Error: [$compile:ctreq] Controller 'form', required by directive 'mydirective', can't be found! http://errors.angularjs.org/1.4.2/$compile/ctreq?p0=form&p1=mydirective

How this can be fixed?

like image 333
onkami Avatar asked Jul 14 '15 12:07

onkami


People also ask

How do you test a Jasmine directive?

We should Unit Test directives by mocking all dependencies with jasmine mocks and spies. We should also Shallow / Deep Test directives using concrete Components (Compiled DOM). A reasonable approach is to create TestComponent or pick up any component which uses the directive we want to test.

What does detectChanges do in Angular Jasmine tests?

detectChanges() tells Angular to run change-detection. Finally! Every time it is called, it updates data bindings like ng-if, and re-renders the component based on the updated data. Calling this function will cause ngOnInit to run only the first time it is called.

How do you mock a directive?

A mock directive in Angular tests can be created by MockDirective function. The mock directive has the same interface as its original directive, but all its methods are dummies. In order to create a mock directive, pass the original directive into MockDirective function.


1 Answers

Use

'<form><mydirective></mydirective></form>'

, and use element.find('mydirective') to find the actual directive element.

like image 75
JB Nizet Avatar answered Oct 05 '22 20:10

JB Nizet