Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Unit Testing "Hello World"

    John LindquistJohn Lindquist

    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.

    angularjsAngularJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss