5

In my code there's a line:

var contentWidth = angular.element(document.querySelector('.content'))[0].clientWidth;

It works fine when running the app but when unit testing I get error:

TypeError: 'undefined' is not an object (evaluating 'angular.element(document.querySelector('.content'))[0].clientWidth')

How to solve this issue?

Andrew Sula
  • 939
  • 8
  • 24
Julius
  • 2,473
  • 3
  • 20
  • 26
  • Guessing this is because there is no DOM built when running your unit test. Try building a mock DOM with the elements you need. – pje Aug 12 '14 at 13:24
  • Not really clear on how to do that... – Julius Aug 13 '14 at 10:37
  • Did you attach your compiled element to the document? Otherwise, `document.querySelector()` won't be able to find it. – Thomas Sep 09 '14 at 15:22

1 Answers1

2

Either attach DOM when running test or mock the document.querySelector and angular.element in case you don't need the same.

Remember to remove mock/spy on angular element after test is completed as it will interfere with the jasmine framework which uses that internally.

Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29