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?
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.
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.
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.
Use
'<form><mydirective></mydirective></form>'
, and use element.find('mydirective')
to find the actual directive element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With