Wali
Wali

Reputation: 45

Angularjs Unit Test fails for document.getElementById('#elementId') in controller

Controller Code:

var element = document.getElementById('#elementId');

element.style.display = "block";

When a unit test is executed (which executes the above code in controller), it fails with the following error:

TypeError: Cannot read property 'style' of null at ChildScope.$scope.openTab

How to get document/DOM inside the unit test?

Upvotes: 0

Views: 4991

Answers (1)

codeLover
codeLover

Reputation: 2592

You can try creating a mocked document element with the help of below code:

var mockedDocElement = document.createElement('div');
document.getElementById = jasmine.createSpy('*<<yourElementId>>*').andReturn(mockedDocElement );

In this way for every call to document.getElementById a dummy element will be returned and thus, you can proceed in your method under test without any such exception.

Upvotes: 3

Related Questions