Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS test a directive with replace set to true

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.

like image 989
Eduard Gamonal Avatar asked May 03 '13 15:05

Eduard Gamonal


People also ask

How to test directive AngularJS?

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.

Which directive definition option is used to replace the current element if true?

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.

What is Transclude in AngularJS directive?

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.

What is attrs in AngularJS?

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).


1 Answers

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);
  }));
});
like image 72
codef0rmer Avatar answered Oct 11 '22 13:10

codef0rmer