jeudi 30 juin 2016

Spying on a service call in controller test and returning different values

I'm spying on a service function call in a test spec for a controller, and am returning the result of a promise.

In my test spec I am calling the service function a couple of times and am wanting to resolve with different response data each time.

I currently have this:

beforeEach(function() {
    module('app');
});

beforeEach(inject(function(_MyService_, _$rootScope_, _$controller_, _$q_) {
    myService = _MyService_;
    $rootScope = _$rootScope_;
    $q = _$q_;
    $controller = _$controller_;
    $scope = $rootScope.$new();

    getListPromise = $q.defer();
    spyOn(myService, 'getList').and.returnValue(getListPromise.promise);
}));

describe('When a current financial period with a firstOccurrence greater than one is supplied to the controller', function() {
    beforeEach(function() {
        ctrl = $controller('MyController', {
        });
        getListPromise.resolve({test: 'hello'});
        $scope.$apply();
    });

    describe('Controller activation', function() {
        it('should call myService.getList', function() {
            expect(myService.getList).toHaveBeenCalled();
        });
    });

    describe('getListByQuery', function(){
        beforeEach(function(){
            ctrl.getListByQuery();
            getListPromise.resolve({foo: 'bar'});
            $scope.$apply();
        });
        it('should do something here...', function() {
            expect(...)
        });
    });
});

On initialisation the controller calls my service function, it also calls it from a getListByQuery function in the controller.

I have added a console log to the call to myService.getList in the controller, to log out the value of the result returned in a promise:

myService.getList().then(function(result){
    vm.listData = result;
    console.log(result);
});

So I would expect to see logged out in my test console (using Karma\Jasmine) {test: 'hello'} followed by {foo: 'bar'}

But I see {test: 'hello'} logged out twice.

I'm unsure why this is happening, can any one offer any explanations?

Thanks

Aucun commentaire:

Enregistrer un commentaire