Saturday, April 5, 2014

Writing Unit Test with Jasmine: How to test window.history

Here is how I wrote test to cover my back button directive in AngularJS.

my directive look like this:

app.directive('goBack', function ($window) {
    return {
        template: '<button id="button_goback" title="Go Back to Previous Page" class="btn btn-default" style="">Back</button>',
        restrict: 'E',
        replace: true,
        link: function (scope, element) {
            element.bind('click', function () {
                $window.history.back();
            });
        }
    };
});

and what I want to test is:

- I don't have to test JavaScript library to see if actually url was changed
- I want to make sure when this button is clicked, history.back is called

and here is my test look like:

it('should call history.back when back button is clicked', inject(function () {
        spyOn($window.history, 'back');
        element.find('button').click();
        expect($window.history.back).toHaveBeenCalled();
    }));


2 comments:

  1. One of the reasons for AngularJS’ success is its outstanding ability to be tested. It’s strongly supported by Karma (the spectacular test runner written by Vojta Jína) and its multiple plugins. Karma, combined with its fellows Mocha, Chai and Sinon, offers a complete toolset to produce quality code that is easy to maintain, bug-free and well documented.

    AngularJS Training in Chennai

    ReplyDelete