j_buckley
j_buckley

Reputation: 1936

Jasmine unit test asynchronous controller method

I'm using Jasmine to unit test an Angular controller which has a method that runs asynchronously. I was able to successfully inject dependencies into the controller but I had to change up my approach to deal with the async because my test would run before the data was loaded. I'm currently trying to spy on the mock dependency and use andCallThrough() but it's causing the error TypeError: undefined is not a function.

Here's my controller...

myApp.controller('myController', function($scope, users) {
    $scope.user = {};

    users.current.get().then(function(user) {
        $scope.user = user;
    });
}); 

and my test.js...

describe('myController', function () {
    var scope, createController, mockUsers, deferred;
    beforeEach(module("myApp"));

    beforeEach(inject(function ($rootScope, $controller, $q) {
        mockUsers = {
            current: {
                get: function () {
                    deferred = $q.defer();
                    return deferred.promise;
                }
            }
        };
        spyOn(mockUsers.current, 'get').andCallThrough();

        scope = $rootScope.$new();
        createController = function () {
            return $controller('myController', {
                $scope: scope,
                users: mockUsers
            });
        };
    }));


    it('should work', function () {
        var ctrl = createController();          
        deferred.resolve('me');
        scope.$digest();
        expect(mockUsers.current.get).toHaveBeenCalled();
        expect(scope.user).toBe('me');           
    });
});

If there is a better approach to this type of testing please let me know, thank you.

Upvotes: 1

Views: 1116

Answers (1)

Manuel Mazzuola
Manuel Mazzuola

Reputation: 795

Try

spyOn(mockUsers.current, 'get').and.callThrough();

Depends on the version you have used: on newer versions andCallThroungh() is inside the object and. Here the documentation http://jasmine.github.io/2.0/introduction.html

Upvotes: 4

Related Questions