My <custom-directive>
has replace:true
and template: '<img />'
.
How can I write a unit test for it? I think I want to test that it actually replaces custom-directive with img.
it('should be transformed to <img>', function(){
var elm = $compile('<custom-directive></custom-directive>')(scope);
scope.$digest();
var t = elm.find('img'); // wrong! it replaces the element. it won't find another one inside
//expect(elm).toBeAnImgElement ?
});
I can't find the correct matcher.
The closest case I've seen is checking the contents (elm.html()
or elm.text()
) but my tag is empty.
If a directive creates its own scope and you want to test against it, you can get access to that directive's scope by doing var directiveScope = myElement. children(). scope() - It will get the element's child (the directive itself), and get the scope for that. For testing timeouts, you can use $timeout.
replace: true means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1> tag.
The ng-transclude directive facilitates AngularJS to capture everything that is put inside the directive in the markup and use it somewhere in the directive's template.
scope is an AngularJS scope object. element is the jqLite-wrapped element that this directive matches. attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values. controller is the directive's required controller instance(s) or its own controller (if any).
wrap your directive in a div like:
describe('Directive: custom', function () {
beforeEach(module('App'));
var element, $scope;
it('should be transformed to <img>', inject(function ($rootScope, $compile) {
$scope = $rootScope.$new();
element = angular.element('<div><custom-directive></custom-directive></div>');
element = $compile(element)($scope);
expect(element.children('img').length).toBe(1);
}));
});
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