Unit test with angular element and querySelector


#1

Hi!
I’m making an app with unit test. In the controller I’m making, I use angular.element() and document.body.querySelector(‘my-element’) and I don’t know how I can fake that. The problem isn’t only that I can’t test that but all the tests of this controller are failing with an error like: “TypeError: Cannot read property ‘offsetHeight’ of null”.
I have already searched on google, forum, but I didn’t find any tricks. I only find things when this kind of manipulation is in a directive but not when it is in a controller.
Any idea how I can do that? Can you share your experience please?
Thanks!


#2

yeah… so not dom-manipulations in the controller ^^

you could try to mock the angular.element for that… something like

var elementCalled = false;
angular.element = function (selector) {
    elementCalled = true;
};

but you could also try to use spyOn functionality:

spyOn(angular, 'element');
....
expect(angular.element).toHaveBeenCalled();

But it depends with, what you are doing with the selected dom-node


#3

Thanks for your answer!
I know that the DOM manipulation in a controller is tricky but in this case I don’t have many choices if I want to keep my philosophy of clean code and not overload with directives for nothing. Here is an example of the manipulation I do:

var topScroll = myElement.offsetTop - (window.innerHeight/2);
$ionicScrollDelegate.scrollTo(0, topScroll, true);

With this kind of mock you propose, it’s generating a lot of errors too… I think it would be perfect if it existed a method to inject elements, like we can do with a directive. And I don’t know if there is a way to do that?