0

I'm writing some unit tests for directives in AngularJS using Jasmine and Karma as my test runner. As I'm doing this, I'm wondering whether or not I'm following the best means of setting this up and was hoping someone could help me out.

If my directives use a template by means of templateUrl, is it best to import the actual template, which has proved to be a bit tricky, or to insert a mock of the template using $templateCache and make my assertions of of that? For unit testing, it would seem to me that creating mocks would be the best option because it avoids pulling in the additional resources which clutters up the point of unit testing.

Also, I'm having trouble searching within individual DOM elements, and have been using element.text() to search for content that is bound to the DOM. A lot of the examples I've seen have used this method to search for content, but I was wondering if there was a way to use methods such as getElementById() to isolate portions of the DOM and make assertions based off of small sections at a time.

Say I have the following element as my template:

    <div>
    <div id = "one">data1</div>
    <div id = "two">data2</div>
    </div>

And I compile it into an angular.element. If I do something like element.getElementById("one").innerHTML it doesn't do anything. element.text("data1") will find the values, but it's not very specific.

Thanks

1 Answer 1

2

The question is that directive is meant to bind together user, DOM and Scope. All scope handling shall be done inside a controller (probably bound to your directive through controller: property).

So, you should have a unit testing separated for you controller, without even touching the directive part. Then you shall test your directive. As it's mainly about DOM handling, you might want to test your real template, not a mocked one.

In order to get the elements, as you need, you can use find() method. If you don't use jQuery at all, you can load it (before your AngularJs dependency) on unit testing and use element.find('#one'), for example. All AngularJs elements are extended jQuery elements, if you don't have jQuery on your project, then Angular uses jQLite, and you'll not have the selectors implemented.

Also, take a look here. I give more details on how to test directives at this answer.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.