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();
    }));


Being Productive: Human should never fix JSHint violation by hand (with WebStorm)

command + , to bring preference

search "jshint"

click "enable" and specify config file


above setting will allow you to see violation


then hold down (option + command + L) to bring the screen below


click "Run" to fix all JSHint issue

"Yay"