Unit Testing "Hello World"

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 11 years ago
Updated 5 years ago

This brief intro to unit testing with AngularJS takes a look at how to configure a test, compile an element, and access AngularJS within your tests.

John Lindquist: Let's write some Hello World tests to kind of get an idea of what testing an angular feels. We'll do Hello World for this suite. The first thing we'll need is a before each where we can set up the element we want to test. It's going to be a very simple div, and then inside of the div two plus two. If you've done anything with angular, you know this should evaluate to four.

If we grab this guy, create our element, we'll bring him to the top so we can use him in our test. We'll say that should equal four and that we'll expect our element HTML to be four. From there you can see in the output that it's expecting the expression to be four, which obviously isn't working.

To get this to work we're actually going to grab this. We'll wrap it with this inject keyword which will allow us to use injection inside of here. We can first inject the compiler. We can say we want an element to now be a compiled version of this.

You'll see this will fail, because compiling returns a linking function, so we actually need to invoke it. This will fail because scope is required. We need to inject the root scope and then pass the root scope in. Now it's still failing because we're back to where we were.

The only thing we have left to do is take the root scope. We'll say scope is root scope, and we'll want to use this. If we simply scope and run the digest our test should pass. The expression equals four, and that's how you write your very first Hello World test.

We just want to make sure this is four. By injecting the compiler, compiling the element, passing in the root scope, and then digesting and evaluation the HTML is four, we are green and good to go.

mattjankowski
mattjankowski
~ 9 years ago

This is the first lesson that really didn't work for me. It seemed to require a fair amount of knowledge that wasn't introduced either in the lesson or in previous lessons.

digish a d
digish a d
~ 8 years ago

which lession series does this video belong to?

Markdown supported.
Become a member to join the discussionEnroll Today