/angularjs/

AngularJS Unit Test – part 2

2014-07-05 15:02:03

Test promise

post.controller.js

'use strict';

angular.module('angularJsYoApp')

    .controller('PostCtrl', function ($scope, PostService) {

        $scope.test = "Yo Man";

        PostService.addPost({'id': 1});

        PostService.getPosts().then(function (data) {
            console.log('Success: ', data);
            $scope.posts = data;
        }, function (reason) {
            console.log('Failed: ', reason);
            $scope.posts = reason;
        }, function (update) {
            console.log('Got notification: ', update);
            $scope.posts = update;
        });
    })
;

post.service.js

'use strict';

angular.module('angularJsYoApp')

    .service('PostService', function ($q) {

        this.addPost = function () {

        };

        this.getPosts = function () {

            var deferred = $q.defer();

            setTimeout(function () {
                deferred.notify('It\'s going to be LEGEN -wait for it- DARY');
                if (true) {
                    deferred.resolve({'message': 'yep, we have something for you', 'data': [{'id': 1}, {'id': 2}, {'id': 3}]});
                } else {
                    deferred.reject({'message': 'we don\'t have any posts for you, man', 'data': []});
                }
            }, 500);

            return deferred.promise;
        };
    });

post.controller.test.js

'use strict';

describe('Controller: PostCtrl2', function () {

    var PostCtrl, PostServiceMock, ScopeMock;

    beforeEach(module('angularJsYoApp'));

    beforeEach(inject(function ($controller, _$q_, $rootScope) {

        var deferred = _$q_.defer();
        ScopeMock = $rootScope.$new();

        // arrange
        PostServiceMock = {
            addPost: function () {},
            getPosts: function(){}
        };

        // arrange
        deferred.resolve({'message':'ok',post:[{'id':1}]});
        spyOn(PostServiceMock, 'getPosts').andReturn(deferred.promise);
        spyOn(PostServiceMock, 'addPost').andCallThrough();

        // act
        PostCtrl = $controller('PostCtrl', {
            $scope: ScopeMock,
            PostService: PostServiceMock
        });

        ScopeMock.$apply();
    }));

    it('should use PostService to add new Post', inject(function () {
        // assert
        expect(PostServiceMock.addPost).toHaveBeenCalledWith({'id': 1});
    }));

    it('should use PostService to get Posts', inject(function () {
        // assert
        expect(PostServiceMock.getPosts).toHaveBeenCalled();
        expect(ScopeMock.posts).toEqual({'message':'ok',post:[{'id':1}]});
    }));
});

GitHub