Unit Testing a Directive

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 5 years ago

In this lesson you will unit test a simple AngularJS directive

John Lindquist: Let's move on from testing a "hello, world" example to testing a directive. We have our app module over here. Let's load that up using the module syntax, and then we'll do a new describe. We'll call this "ehSimple" for "egghead simple," and we'll say that it should add a class of plain. Whenever I add this ehSimple directive, it's going to add a plain class, so we'll expect our element to have class of plain.

This should be true. It's false. We want it to be true, so we'll create the directive. Let's add it here first. We'll say "ehSimple."

Now if we create this directive, we'll say "app directive ehSimple," and then we return a function scope and element. We'll just say "element add class simple." Oops, I mean "plain." I typed "plain" there. I meant to type "simple," but whatever. We got it to pass.

That's the simplest way to test a directive. You do a similar thing where you just create the element, you compile it, pass in a scope, and then you can start testing things on the element by loading up your module using this syntax.

If this is starting to look intimidating, don't worry. This stuff right here gets really repetitive on all of your tests. You're going to do this all the time, where you just inject things and then reference them throughout your tests. Writing these really isn't that difficult.

egghead
egghead
~ 9 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today