lundi 27 juillet 2015

How to avoid errors with unit testing a controller?

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://ift.tt/1D7IWPb

Aucun commentaire:

Enregistrer un commentaire