How to add a div to the DOM in AngularJS unit tests?

Maarten picture Maarten · Aug 1, 2013 · Viewed 9k times · Source

I'm using the following code in a directive to place a tool tip

var bodyoffset = document.querySelector(".smallcontainer-content").getBoundingClientRect();
var width = elm.width();
if(bodyoffset != undefined){
    var tooltipDiv = document.querySelector(".tooltip");
    angular.element(tooltipDiv).css("top", offset.top-bodyoffset.top+"px");
    angular.element(tooltipDiv).css("left", offset.left-bodyoffset.left+width+5+"px");
}

This doesn't work in a unit test as the div the class 'smallcontainer' is on doesn't exist. How can I make sure the div is created in the unit test so that I can test all my functions?

Answer

Maarten picture Maarten · Aug 1, 2013

This is how I managed to do it:

beforeEach(inject(
    ['$compile','$rootScope', function(_$compile_) {
        var html = '<div class="smallcontainer-content"></div>';
        angular.element(document.body).append(html);
        elm = angular.element('<form name="form"><input name="password" id="passwordInput" data-ng-model="password" size="25" type="password" maxlength="20" tabindex="1" autofocus  data-my-password-check></form>');
        $compile(elm)($rootScope);
        form = $rootScope.form;

    }]
));

The important part here which adds the html to the document is the angular.element().append().

I found this in the midway testing code example of http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html#testing-filters