AngularJS – Test driven development tutorial

AngularJS is a great framework that allow separation of concerns pattern, if you’re new to AngularJS, maybe you need to learn differences between JQuery and AngularJS i’ve explained here https://creativcoders.wordpress.com/2014/05/11/differences-between-jquery-and-angularjs/.

For this first tdd with Angular, we just want a simple directive to indicate in our menu what our current route is. We can declare what we want in our view:

//View in the html
//<a href="/hello">Hello</a>

//Test begins here:
it( 'should add "active" when the route changes', inject(function() {
    var elm = $compile( '<a href="/hello">Hello</a>' )( $scope );

    $location.path('/not-matching');
    expect( elm.hasClass('active') ).toBeFalsey();

    $location.path( '/hello' );
    expect( elm.hasClass('active') ).toBeTruthy();
}));

If we run our test, it will fail because initial link has no class ‘active’. We can now declare a directive to add a class on urlChange without having to modify the html.

.directive( 'whenActive', function ( $location ) {
    return {
        scope: true,
        link: function ( scope, element, attrs ) {
            scope.$on( '$routeChangeSuccess', function () {
                if ( $location.path() == element.attr( 'href' ) ) {
                    element.addClass( 'active' );
                } else {
                    element.removeClass( 'active' );
                }
            });
        }
    };
});

Well done for your first test driven development in AngularJS.

Advertisements
AngularJS – Test driven development tutorial

One thought on “AngularJS – Test driven development tutorial

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s