1

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh thank you, I'm using 2.0 and I was looking at an example from an older version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.