0

I am trying to unit test a controller. This is my controller:

app.factory('myService', function ($q) {
    var callMe = function (user) {
        var pr = $q.defer();
        pr.resolve('Hello ' + user);
        return pr.promise;

        //$timeout(function(){
        //    pr.resolve('Hello ' + user);
        //    return pr.promise;
        //},4000);

    }
    return {callMe: callMe};
});



app.controller('myCtrl',function($scope,myService){
    $scope.callService = function(){
        $scope.callMeValue = myService.callMe('lo');
    }
})

This is my test:

beforeEach(
    inject(function (_$rootScope_, $controller, _myService_, _myServiceTimeout_,$q) {
    myService = _myService_;
    myServiceTimeout = _myServiceTimeout_;
    $scope = _$rootScope_.$new();

    ctrl = $controller('myCtrl', {
        $scope: $scope,
        someService: someServiceMock
    });

    someServiceMock.callMe.andReturn($q.when('Ted'));
}));


it('ctrl test', function () {
    $scope.callService();
    expect(myService.callMe).toHaveBeenCalled();
});

Here are the errors I am getting:

TypeError: someServiceMock.callMe.andReturn is not a function

and:

Error: Expected a spy, but got Function.

How can I fix this?

plunkr: http://plnkr.co/edit/EM1blTOlg5fw5wq6OFcr?p=preview

1 Answer 1

1

Your example contains several bugs.

  1. If you use timeout in code, in test you must use $timeout.flush() (scope.$apply not enough)
  2. $timeout is promise, you not need create own promise
  3. $timeout is promise, you must return it

    app.factory('myServiceTimeout', function ( $timeout) {
        var callMe = function (user) {
            return $timeout(function(){
                return 'Hello ' + user;
            },4000);
    
        }
        return {callMe: callMe};
    });
    
    
    it('test2',function(){
        var result;
        myServiceTimeout.callMe('Ruud').then(function(ret)
        {
            result = ret;
        });
    
        $timeout.flush()
        expect(result).toBe('Hello Ruud');
    });
    

whole exemple: http://plnkr.co/edit/cqzTYwfs94Xqyz5MTxeE?p=preview

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

Comments

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.