Unit Testing "Hello World"

AngularJS - Unit Testing "Hello World"AngularJS Video Tutorial by John 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.


The ability to reply to discussions is limited to PRO subscribers. Want to join in the discussion? Click here to subscribe now.
egghead.io
Avatar

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.



As a PRO subscriber, the full source for this lesson is available to download alongside the HD video.
Click here to subscribe now

directive.spec.js

describe("Hello world", function() {
    var element;
    var $scope;
    beforeEach(inject(function($compile, $rootScope) {
        $scope = $rootScope;
        element = angular.element("<div>{{2 + 2}}</div>");
        element = $compile(element)($rootScope)
    }))

    it('should equal 4', function() {
    $scope.$digest()
    expect(element.html()).toBe("4");
  })
})

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.

Tech logo bar

Don't miss out on the latest PRO lessons.

Get Your PRO Subscription Now

Because you like code... not PowerPoint slides.