Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 363
Maarten Avatar asked Aug 01 '13 10:08

Maarten


People also ask

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

What is fixture detectChanges ()?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement.

How do I run a test case in AngularJS?

Testing in AngularJS is achieved by using the karma framework, a framework which has been developed by Google itself. The karma framework is installed using the node package manager. The key modules which are required to be installed for basic testing are karma, karma-chrome-launcher ,karma-jasmine, and karma-cli.


1 Answers

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

like image 152
Maarten Avatar answered Oct 04 '22 15:10

Maarten