Showing posts with label unit test. Show all posts
Showing posts with label unit test. Show all posts

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


Sunday, September 22, 2013

python mock: Diffference between Mock and MagicMock

note: why use mock/fake/stub object for unit test:

Using mock objects allows developers to:
  1. write and unit-test functionality in one area without actually calling complex underlying or collaborating classes
  2. focus their tests on the behavior of the system under test (SUT) without worrying about its dependencies
When mock objects are replaced by real ones then the end-to-end functionality will need further testing. These will be integration tests rather than unit tests.

Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used.

Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway) - (per http://www.voidspace.org.uk/python/mock/#quick-guide)

example:

>>> import mock
>>> mock1 = mock.Mock()
>>> mock2 = mock.MagicMock()

>>> mock2.__str__.return_value = 'foobarbaz'
>>> str(mock2)
'foobarbaz'
>>> mock2.__str__.assert_called_with()

>>> mock1.__str__.return_value = 'foobarbaz'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'method-wrapper' object has only read-only attributes (assign to .return_value)

# ah, there it is, i have to configure __str___ behavior

>>> mock1.__str__ = mock.Mock(return_value='wheeeeee')
>>> str(mock1)
'wheeeeee'