lundi 7 décembre 2015

How to prevent real service from being called when using spyOn? Getting Unexpected request: POST error

I'm trying to use spyOn to mock the response when a function is called, however, when I $digest or $apply $rootScope to process the call back, it's giving me a

Error: Unexpected request: POST /getActiveCountries

message as if it's still trying to call the real service.

Here's the test code:

describe('EditOfferCtrl with fake services', function(){
    beforeEach(module('app'));

    var $controller;
    var $q;
    var $rootScope;
    var getDataService;

    beforeEach(inject(function(_$controller_, _$q_, _$rootScope_, _getDataService_){
        $controller = _$controller_;
        $q = _$q_;
        $rootScope = _$rootScope_;
        getDataService = _getDataService_;
    }));

    describe('Edit Offer Page Controller with fake services', function() {
        var $scope = {};
        var editOffer;
        var results = { data: 'fake'};

        beforeEach(function() {
            editOffer = $controller('EditOfferCtrl', {$scope: $scope});
        });

        it('Core functions should work', function() {
            spyOn(getDataService, 'getData').and.callFake(function() {
                var deferred = $q.defer();
                deferred.resolve(results);
                return deferred.promise;
            });

            $rootScope.$apply(); // $rootScope.$digest() gives same results
            console.log(editOffer.getActiveCountries());


        });
    });
});

Aucun commentaire:

Enregistrer un commentaire