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.

4

1 回答 1

4

尝试

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

取决于您使用的版本:在较新的版本上,并且CallThroungh() 在对象内部。这里的文档http://jasmine.github.io/2.0/introduction.html

于 2014-06-30T19:38:33.697 回答