Testing Underscores

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 11 years ago
Updated 6 years ago

AngularJS injectors understand aliased for core injectables such as $rootScope in unit tests. If you surround your injected object with underscores _$rootScope_ it will be understood and injected into your test by Angular. This allows you to use a local alias of the same name.

John Lindquist: A very common practice you'll see when testing is, when you inject something like rootScope, instead of just injecting it like I normally would, they would put an underscore in front of it and an underscore behind it.

I'm just going to do it the slow way here. What this allows you to do is that you can easily name something rootScope and assign it to _rootScope, and then you have a reference to rootScope which you can use.

Basically all that Angular's doing is stripping these out as a convenience. There's really nothing going on here. It's not some sort of different rootScope, it's the exact same rootScope, and the same thing works for the compile. I'm just going to rename this one. If I wanted to get the compiler, I can just assign it to compile, and then I can have the compiler available anywhere I want as well.

That's just a very common practice, because all these are usually used for injecting and assigning to something and then bringing this guy up so you can use it throughout your tests. You'll see this everywhere when reading other people's tests.

Let's just clean up this very last line here to make it more of the standard way of doing things.

egghead
egghead
~ 7 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